|
-
Nov 25th, 2001, 12:57 AM
#1
Thread Starter
Fanatic Member
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?
Alcohol & calculus don't mix.
Never drink & derive.
-
Nov 25th, 2001, 01:14 AM
#2
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.
-
Nov 25th, 2001, 04:25 PM
#3
Thread Starter
Fanatic Member
Ok, that works, but why does it have to be outside of the class?
Alcohol & calculus don't mix.
Never drink & derive.
-
Nov 25th, 2001, 04:48 PM
#4
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.
-
Nov 25th, 2001, 05:36 PM
#5
transcendental analytic
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
Use  
writing software in C++ is like driving rivets into steel beam with a toothpick.
writing haskell makes your life easier:
reverse (p (6*9)) where p x|x==0=""|True=chr (48+z): p y where (y,z)=divMod x 13
To throw away OOP for low level languages is myopia, to keep OOP is hyperopia. To throw away OOP for a high level language is insight.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|