Operator Overload

V

Victor Bazarov

Rama said:
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
 
O

osmium

Rama said:
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::eek:perator>(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();
}
 
J

Jerry Coffin

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top