Skip to main content
gamedev.net
🔒 Locked

+ operator overload

Started by squicklid 3 replies 450+ views
Original Post
squicklid
squicklid
How do you overload an operator so that you can do this:
//A String Class
class S {};

int main()
{
    S meat;
    S cows;

    //THIS HERE, with having the class on the rhs
    //and a char * on the lhs
    meat = "hens" + cows;

    return 0;
}
[\code]

Because with strings, the order matters   
Sneftel
Sneftel
You need to make the operator-overload a global function, as opposed to a class member function.


class A { ... };

A operator+(const char* lhs, const A &rhs) { ... }



"Sneftel is correct, if rather vulgar." --Flarelocke
Zipster
Zipster
Making the overload a friend of your class can also be a good idea, depending exactly on what it is you want to do.
Amma
Amma
You can''t, and should therefore write:

''meat = S("hens") + cows;''

instead of just
''meat = "hens" + cows;''

-----------------------------
Amma
-----------------------------Amma
Onemind
Onemind
Sneftel is right, the only way to overload something like that is thru a global operator overload.

You can define a function as a friend function by placing it in the class you want to be friends with, and putting the word "friend" in front of it.

Ex.


class A
{
...
public:

// this function is still global even tho it is in a class
friend A operator+(const char* lhs, const A &rhs); // friend prototype
};

// global overloaded + operator
A operator+(const char* lhs, const A &rhs) { ... }

Topic Locked

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

Sign in to reply to this topic.