next up previous
Next: Making it general Up: A short C++/OO tutorial: Previous: Making it useful (i)

Making it useful (ii)

Toggle Background


What else can we do with polynomials? We may add them. Here it goes: Polynomial5.C

 1 class Polynomial : public vector<double> {
 2 public:
 3     // ...
 4     // declare addition operator
 5     Polynomial operator + (const Polynomial & p) const;
 6     // ...
 7 };
 8 
 9 Polynomial Polynomial::operator + (const Polynomial & p) const
10 {
11 Polynomial  r(*this);   // copy left polynomial into result
12     for ( unsigned int i=0 ; i<p.size() ; ++i ) // loop over right polynomial
13         if ( i<size() ) // check if coefficient index exist in result polysnomial
14             r[i] += p[i];   // yes: add coefficients from right polynomial
15         else
16             r.push_back(p[i]);  // no: append coefficients from right polynomial
17     return r;   // return result
18 }
19 
20 int main()
21 {
22 Polynomial  p(4);
23     p[0] = 1;   // 1*x^0
24     p[4] = 2;   // 2*x^4
25 
26 Polynomial  q(2);
27     q[0] = 1;   // 1*x^0
28     q[1] = 2;   // 2*x^1
29     q[2] = 3;   // 3*x^2
30 
31     cout << "p = " << p << endl;    // print it
32     cout << "q = " << q << endl;    // print it
33     cout << "p(3.4) = " << p(3.4) << endl;  // evaluate and print it
34     cout << "q(3.4) = " << q(3.4) << endl;  // evaluate and print it
35     cout << "p(3)+q(3) = " << p(3)+q(3) << endl;
36     cout << "p+q = " << p+q << endl;
37     cout << "(p+q)(3) = " << (p+q)(3) << endl;
38     return 0;
39 }
Download Full Source

Line by line walk through:

Line 5:
Declare: There is a new operator "+" taking one argument of a double returning a double (the second argument is once again implicit by this)
Line 9:
Implementation of the operation "+" for polynomials.
Line 26:
Define a second polynomial.
Line 36,37:
Use the "+" operation.

The program will return:

p = 2*x^4 + 1
q = 3*x^2 + 2*x^1 + 1
p(3.4) = 268.267
q(3.4) = 42.48
p(3)+q(3) = 197
p+q = 2*x^4 + 3*x^2 + 2*x^1 + 2
(p+q)(3) = 197

Further extensions are obvious...



Michael Hanrath 2006-05-02