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
|
// Operator Overloading
#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;}
ThreeD operator+(ThreeD op2); // op1 is implied
//ThreeD operator=(ThreeD op2); // op1 is implied
void show();
};
//Overload +.
ThreeD ThreeD::operator+(ThreeD op2)
{
ThreeD temp;
temp.x = x + op2.x; // These are integer addition
temp.y = y + op2.y; // and the + retains its original
temp.z = z + op2.z; // meaning relative to them
return temp;
}
// Overload assignment.
//ThreeD ThreeD::operator=(ThreeD op2)
//{
// x = op2.x; //these are integer assignments
// y = op2.y; // and the = retains its original
// z = op2.z; // meaning relative to them
// return *this;
//}
// 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 + c; // add a, b, and c together
cout << "Value of c after c = a + b + c: ";
c.show();
cout << '\n';
c = b = a; // demonstrate multiple assignment
cout << "Value of c after c = b = a: ";
c.show();
cout << "Value of b after c = b = a: ";
b.show()
;
return 0;
}
|