Skip to main content
gamedev.net
🔒 Locked

C++ operator overloading

Started by Asuralm Jan 17, 2008 at 8:47 AM 2 replies 950+ views
Original Post
Asuralm
Asuralm
Hi all: The code is as follows:
[source lang='cpp']
class My_Class{
public:
....
    inline My_Class operator*(float d){
        ....;
    }
....
}

And when I multiply a float float on the left hand side, like following, it doesn't work.

int main(){
    My_Class x;
    float d;
    My_Class y = d * x;
}

But it works like:

int main(){
    My_Class x;
    float d;
    My_Class y = x * d;
}

Could anyone tell me why this happens please? And how can I overload the operator properly so both left and right handside can work? Thanks
Asura
SiCrane
SiCrane
In order to get a the left hand side of operator* to work with a primitive, you need to declare a non-member operator* overload. Ex:
MyClass operator*(float lhs, const MyClass & rhs) {  do stuff}

Note that this only declares a float * MyClass overload. If you also want a MyClass * float overload you either need to declare the member function overload or another non-member overload with the argument types reversed.
Asuralm
Asuralm
Thanks.

And I have another question.

If I have a class called my class, how can I overload the unary operator "-" please?
Like:
My_Class x;My_Class y = -x;


Should it be like:
My_Class operator-(){...}


Is it correct?
Thanks
Asura

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.