-
Question on operators
Ok, I have been looking at some other posts here about this but I have a question.
Code:
class INT
{
public:
INT() {}
INT(int c) {a = c;}
~INT() {}
int getVal() {return a;}
void operator = (int x) {a = x;}
void operator = (INT x) {a = x.getVal();}
INT& operator + (int x) {a += x; return *this;}
INT& operator + (INT& x) {a += x.getVal(); return *this;}
private:
int a;
};
I want to be able to do "INT aa=5; INT bb=7; INT cc = aa+bb" but I am not sure how. Can someone help me?
-
Code:
INT operator + (INT lhs, INT rhs)
{
INT tmp;
tmp = lhs.getVal() + rhs.getVal()
return tmp;
}
Put that OUTSIDE of the class declaration (so it isnt a member of the class) and it should work. Remove the "INT lhs" part, and change any references to lhs to "a", should make it work the way you have it. The operator inside the overloaded + operator should NOT be +=.
Also, beware of including windows.h. INT is typedef ed to int.
Z.
-
Ok, that works, but why does it have to be outside of the class?
-
I find that to be the easiest way. It doesnt have to be, just my preference. If you want it inside the class do this:
Code:
INT operator + (INT rhs)
{
INT tmp;
tmp = a + rhs.getVal();
return tmp;
}
...if i remember correctly.
Z.
-
Using a global operator, the thing is that the compiler is able to cast up the first operand to int which saves you from a lot of recoding, you could of course use templates and template specilisation which i would ;)