Total members 11889 |It is currently Fri Mar 29, 2024 2:40 am Login / Join Codemiles

Java

C/C++

PHP

C#

HTML

CSS

ASP

Javascript

JQuery

AJAX

XSD

Python

Matlab

R Scripts

Weka





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;
}




_________________
Please recommend my post if you found it helpful


Author:
Beginner
User avatar Posts: 95
Have thanks: 2 time
Post new topic Reply to topic  [ 1 post ] 

  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






Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
All copyrights reserved to codemiles.com 2007-2011
mileX v1.0 designed by codemiles team
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com