1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
|
// My last assignment using Notepad ++
//Use friend operator functions.
#include <iostream>
using namespace std;
class ThreeD {
int x, y, z; // 3-d coordinates
public:
ThreeD() {x = y = z = 0;}
ThreeD(int i, int j, int k) {x=i; y=j; z=k; }
friend ThreeD operator+(ThreeD op1, ThreeD op2); //1. Here operator+() is a friend of ThreeD
void show();
};
//The + is now a friend function
ThreeD operator+(ThreeD op1, ThreeD op2)// 2. Notice that 2 parameters are required
{
ThreeD temp;
temp.x = op1.x + op2.x;
temp.y = op1.y + op2.y;
temp.z = op1.z + op2.z;
return temp;
}
// Show X,Y,Z coordinates
void ThreeD::show()
{
cout << x << ", ";
cout << y << ", ";
cout << z << "\n";
}
int main()
{
ThreeD a(1,2,3), b(10,10,10), c;
cout << "Original value of a: ";
a.show();
cout << "Original value of b: ";
b.show();
cout << "\n";
c = a + b; // add the values a & b together
cout << "Value of c after c = a + b: ";
c.show();
cout << "\n";
c = a + b + c; // add the values a,b& c together
cout << "Value of c after c = a + b + c: ";
c.show();
cout << "\n";
//Demonstrate multiple assignment
c = b = a;
cout << "Value of c after c = b = a: ";
c.show();
cout << "Value of b after c = b = a: ";
b.show();
return 0;
}
|