Results 1 to 5 of 5

Thread: Question on operators

  1. #1

    Thread Starter
    Fanatic Member Wynd's Avatar
    Join Date
    Dec 2000
    Location
    In a bar frequented by colossal death robots
    Posts
    772

    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.

  2. #2
    Zaei
    Guest
    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.

  3. #3

    Thread Starter
    Fanatic Member Wynd's Avatar
    Join Date
    Dec 2000
    Location
    In a bar frequented by colossal death robots
    Posts
    772
    Ok, that works, but why does it have to be outside of the class?
    Alcohol & calculus don't mix.
    Never drink & derive.

  4. #4
    Zaei
    Guest
    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.

  5. #5
    transcendental analytic kedaman's Avatar
    Join Date
    Mar 2000
    Location
    0x002F2EA8
    Posts
    7,221
    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
  •  



Click Here to Expand Forum to Full Width