An operator overload is a special type of function, but nevertheless just a function. Many operator overloads can either be defined
within the class, or outside of it.
When you have a function defined within a class, you can think of the implicit 'this' object as being the first argument of the function.
This is the same in your first code. It's the same as saying
1 2 3 4 5 6 7
|
class obj {
// ...
int operator+(const obj b)
{
return this->data + b.data;
}
}
|
When you define a function such that it isn't a member function, there is no implicit 'this' parameter.
1 2 3 4
|
int operator+(const obj x)
{
return x;
}
|
Here, you are not adding anything. You are simply trying to take in an 'obj' parameter, and return it as an int, which probably is not what you want.
To define it outside of the class, you would need to something like:
1 2 3 4
|
int operator+(const obj a, const obj b)
{
return a.data + b.data;
}
|
Note that this definition is very weird, and may be an abuse of operator overloading. If you add two 'obj' objects together, wouldn't you expect it to return another 'obj'?
By a way,i also want to know whether the statement below is ture or not.
Statement:"We should always pass the same parameter number,when we overloading an opertor,as an opertor needs(when we use that operator alone)to parameter list. |
I don't know what that means.