Operator Overloading

Posted on June 22, 2013. Filed under: C++ |


In c++ you can overload operators such as +, -, *, / etc.
The syntax is: add keyword “operator” before an operator, then treat the whole string as a function.

For example, to overwrite + operator.

In Sally.h

#ifndef SALLY_H
#define SALLY_H

class Sally
{
public:
int num;
Sally();
Sally(int);
Sally operator+ (Sally); //overwrite operator+,
//have a Sally object as function parameter
//return a Sally object
};
#endif

=========
In Sally.cpp

#include
#include
using namespace std;

Sally::Sally()
{}

Sally::Sally(int a) {
num = a;
}

Sally Sally::operator+(Sally aso) {
Sally newSally;
newSally.num = num + aso.num;
return(newSally);
}

====================
In main.cpp

#include
#include “Sally.h”
using namespace std;

main()
{
Sally a(3);
Sally b(4);
Sally c;      //create a Sally object

c = a + b;   // create another Sally object, assign num = a.num + b.num,

//then return the Sally object, assign to c.
bout << c.num<<endl;  //value is 7
}

Advertisements

Make a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Liked it here?
Why not try sites on the blogroll...

%d bloggers like this: