76 3 Numerical differentiation and interpolation
ostream&operator<< (ostream& o,constVector& v)
{v.print(o);returno;}
// must return ostream& for nested output operators:
cout <<"some text..."<< w;
// this is realized by these calls:
operator<< (cout,"some text...");
operator<< (cout, w);
We can redefine the multiplication operator to mean the innerproduct of two vectors:
doublea = v*w;// example on attractive syntax
classVector
{
...
// compute (*this)*w
double operator*(constVector& w)const;
...
};
doubleVector::operator*(constVector& w)const
{
return inner(w);
}
// have some Vector u, v, w; double a;
u = v + a*w;
// global function operator+
Vectoroperator+ (constVector& a,constVector& b)
{
Vector tmp(a.size());
for(inti=1; i<=a.size(); i++)
tmp(i) = a(i) + b(i);
returntmp;
}
// global function operator*
Vectoroperator*(constVector& a,double r)
{
Vector tmp(a.size());
for(inti=1; i<=a.size(); i++)
tmp(i) = a(i)*r;
returntmp;
}
// symmetric operator: r*a
Vectoroperator*(double r,constVector& a)
{returnoperator*(a,r);}
3.3.2.1 Classes and templates in C++
We can again use templates to generalize our class to accept other types than just doubles.
To achieve that we use templates, which are the native C++ constructs for parameterizing
parts of classes, using statements like
template
classVector