Programming and Graphics

(Kiana) #1

6.16 Class templates 195


void point<T>::move(T dx, T dy)
{
x=x+dx; y=y+dy;
}

// overload + :

template <class T>
point<T> point<T>::operator + (point<T> param)
{
point<T> add;
add.x = x + param.x;
add.y = y + param.y;
return add;
}

The following main code uses the point class template:


int main()
{
point<int> A = point<int>(1, 2);
A.print();
A.move(4, -5);
A.print();

point<float>B(3.2, 4.9);
cout << B.getx() << " " << B.gety() << endl ;

point<string> C("day", "young");
C.print();
C.move("s","ster");
C.print();

point<string> D("viet", "kambo");
point<string> E("nam", "dia");
point<string> F=D+E;
F.print();

return 0;
}

Running the code produces on the screen:


12
5-3
3.2 4.9
day young
days youngster
vietnam kambodia
Free download pdf