Total members 9951 | Gratitudes |It is currently Sat Feb 11, 2012 9:39 am Login / Join Codemiles


All times are UTC [ DST ]




Post new topic Reply to topic  Quick reply  [ 1 post ] 
Author Code Snippet
 Code subject: unary operator overloading
PostPosted: Thu Nov 13, 2008 8:01 pm 
Offline
Beginner
User avatar

Joined: Sun May 25, 2008 5:34 pm
Posts: 95
Has thanked: 2 time
Have thanks: 1 time

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


TOP
 Profile Send private message  
Reply with quote  
Post new topic Reply to topic Quick reply  [ 1 post ] 
Quick reply


  


 Similar topics
 Topic title   Forum   Author   Comments 
 working of bitwise ~ operator  Java  Anonymous  1
 stream operator  C-C++  mileloader  0
 Sizeof Operator  C++ examples  mileloader  0
 Function Overloading  C++ examples  mileloader  0
 overloading << and >>  C-C++  AskBot  1

All times are UTC [ DST ]


Users browsing similar codes

Users browsing this forum: No registered users and 1 guest



Jump to:  
Previous Code Snippet | Next Code Snippet 




Home
General Talks
Finished Projects
Code Library
Games
Tutorials

Java
C/C++
C-sharp
php
Script
JSP/Servlets
Ajax
ASP/ASP.net
Google SEO
Database
Communications
Phpbb3 styles
Photoshop tutorials
Flash tutorials
Find a job






Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
All copyrights reserved to codemiles.com 2007-2011
mileX v1.0 designed by codemiles team