By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,819 Members | 1,173 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,819 IT Pros & Developers. It's quick & easy.

Operator Overload

P: n/a
wht is operator overloading, how you overload an operator

Jul 23 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
Rama wrote:
wht is operator overloading, how you overload an operator


You define a function using the special syntax for defining an operator:

[<return_value_type>] operator @ ( [<arguments>] )

The keyword 'operator' and the parentheses are necessary. The return
value type is not necessary for type conversion operators. Arguments
may be necessary depending on what operator you overload. The '@' sign
in the syntax designates the place where you put the operator sign. For
example, here is the single minus overload for struct T:

struct T {
T operator -() const;
};

What book are you reading that doesn't explain operator overloading?

V
Jul 23 '05 #2

P: n/a
"Rama" writes:
wht is operator overloading, how you overload an operator


Operator overloading is a means of calling a class member function when an
operator occurs in the source code. It allows nicer looking source code
when there is some reasonable similarity between the operator symbols and
some function to be performed on an object. One of the more appealing
examples is concatenation of a string, which could be codified as '+'.
Another nice one is that operators can be applied to complex numbers where
there is a one to one correlation between most of the arithmetic symbols for
real numbers and complex numbers. Beware, it is easy to be tempted to let
operator overloading run amok and use it where there is a dubious
relationship between the operators and the resulting action.

A simple example is as follows:
---------------------------
#include <iostream>

using namespace std;

class C
{
public:
C(int na) {n = na;}
bool operator>(C rhs); // rhs - right hand side
private:
int n;
};
//-----------------------
bool C::operator>(C rhs)
{
if(n > rhs.n)
return true;
else
return false;
}
//=====================
int main()
{
C c(1024);
C d(2048);

bool x, y;
x = c>d;
y = d>c;

cout << x << ' ' << y << endl;
cin.get();
}

Jul 23 '05 #3

P: n/a
osmium wrote:

[ ... ]
Operator overloading is a means of calling a class member function
when an operator occurs in the source code.


Leave out "class member" in that sentence and it'll be more accurate.

--
Later,
Jerry.

The universe is a figment of its own imagination.

Jul 23 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.