Switch to full style
C++ code examples
Post a reply

unary operator overloading

Thu Nov 13, 2008 8:01 pm

unary operator overloading
cpp code
#include <iostream>
using namespace std;

class MyClass {
int x, y, z;
public:
MyClass() {
x = y = z = 0;
}
MyClass(int i, int j, int k) {
x = i;
y = j;
z = k;
}

MyClass operator+(MyClass op2);
MyClass operator=(MyClass op2);
MyClass operator++();

void show() ;
} ;

// Overload +.
MyClass MyClass::operator+(MyClass op2)
{
MyClass temp;

temp.x = x + op2.x; // These are integer additions
temp.y = y + op2.y; // and the + retains is original
temp.z = z + op2.z; // meaning relative to them.
return temp;
}

// Overload assignment.
MyClass MyClass::operator=(MyClass 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;
}

// Overload the prefix version of ++.
MyClass MyClass::operator++()
{
x++; // increment x, y, and z
y++;
z++;
return *this;
}

// Show X, Y, Z coordinates.
void MyClass::show()
{
cout << x << ", ";
cout << y << ", ";
cout << z << endl;
}

int main()
{
MyClass a(1, 2, 3), b(10, 10, 10), c;
a.show();
b.show();

c = a + b; // add a and b together
c.show();

c = a + b + c; // add a, b and c together
c.show();

c = b = a; // demonstrate multiple assignment
c.show();
b.show();

++c; // increment c
c.show();

return 0;
}




Post a reply
  Related Posts  to : unary operator overloading
 What is Operator Overloading? !!!     -  
 operator overloading     -  
 Operator overloading easy code     -  
 overloading << and >>     -  
 Function Overloading     -  
 Using the ? Operator     -  
 What is the % operator     -  
 operator int()     -  
 trinary operator     -  
 Sizeof Operator     -  

Topic Tags

C++ Basics