Sign in to follow this  
avocados

Can't overload operator=

Recommended Posts

avocados    124
Wiki says you can overload this in C++ but Visual Studio 2010 says it is not a member function. Just curious, what's up?
[code]void operator=( v3f &a, v3i b ) { ; } //error
void operator-=( v3f &a, v3i b ) { ; } //no error
[/code]

Share this post


Link to post
Share on other sites
Wooh    1088
For some reason operator= must be inside the class definition. Make it a member of v3f and it will work fine.

Share this post


Link to post
Share on other sites
NightCreature83    5006
[quote name='avocados' timestamp='1306016630' post='4813989']
Wiki says you can overload this in C++ but Visual Studio 2010 says it is not a member function. Just curious, what's up?
[code]void operator=( v3f &a, v3i b ) { ; } //error
void operator-=( v3f &a, v3i b ) { ; } //no error
[/code]
[/quote]




[quote name='Wooh' timestamp='1306017148' post='4813993']
For some reason operator= must be inside the class definition. Make it a member of v3f and it will work fine.
[/quote]
That is not weird at all as this is an assignment operator and if you overload an [url="http://en.wikipedia.org/wiki/Assignment_operator_(C%2B%2B)"]assignment operator[/url] you'd better implement a copy constructor and destructor for that class as well([url="http://en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming)"]more info[/url]). The usual prototype for this is:
[code]
T& operator=(T rhs)
{
//Do your stuff
return *this;
}
[/code]
T can stand for any user defined type here and should be the class name this method is part of.
You return a reference to this so that you can chain assignments which C++ allows you to do.
It makes no sense to declare this particular operator outside of a class as you wouldn't be able to assign the private variables form rhs to your current object.

If you would like to assign another type to this particular variable type you need to add a constructor to this class that takes that type as a parameter and can construct an instance of this type. Read up on construction of objects in C++ to understand why this happens this way, you should also know what happens when a copy constructor or assignment operator is called, as sloppy implementations can cause a overhead or even worse problems(shallow copies).

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this