5.1 A template class with friends
Solution
Here is the header file point.h:
template<class C> class Point; template<class C> std::ostream& operator<<(std::ostream& s, const Point<C>& p); template<class C>class Point { private: C x, y; public: Point(C, C); Point(); C getx () const; C gety () const; Point<C>& move(C, C); C distance_to(Point); friend std::ostream& operator<< <>(std::ostream&, const Point<C>&); };
Notice the two declarations before the generic class point defintion. And notice the <> before the parameters in the friend declaration
Here is the point.cc:
#include <cmath> #include <iostream> #include "point.h" template<class C> Point<C>::Point(C x_coord, C y_coord): x(x_coord), y(y_coord){ } template<class C> Point<C>::Point(): x(0.0), y(0.0){ } template<class C> C Point<C>::getx () const{ return x; } template<class C> C Point<C>::gety () const{ return y; } template<class C> Point<C>& Point<C>::move(C dx, C dy){ x += dx; y += dy; return *this; } template<class C> C Point<C>::distance_to(Point p){ return sqrt((x - p.x) * (x - p.x) + (y - p.y) * (y - p.y)); } template<class C> std::ostream& operator<< (std::ostream& s, const Point<C>& p){ return s << "(" << p.x << "," << p.y << ")" ; }
Finally, prog.cc with main:
#include <iostream> #include <string> #include "point.cc" // Notice inclusion of cc files, in order to // instantiate the templates for int and double. // Else lots of linker errors will occur. // This treats templates in the same way as inline functions. // The C++ Programming Language, 3ed ed, page 350-351. int main(){ Point<double> pd1, pd2(1,2); Point<int> pi1, pi2(3,4); Point<char> pc1, pc2(97, 98); // Char 97 = 'a' pd2.move(1,1); pi2.move(1,1), pc2.move(1,1), std::cout << "pd2: " << pd2 << std::endl; // (2,3) std::cout << "pi2: " << pi2 << std::endl; // (4,5) std::cout << "pc2: " << pc2 << std::endl; // (b,c) }
Generated: Tuesday March 26, 2013, 13:03:53