what complier do when overloads operators in a class?

ake "+" as an example.when overloading operator+ in a class:

1
2
3
4
5
6
7
8
class obj{
    public:
    int data;
    obj(){data=1;}
    int operator+(const obj b){
        return data+b.data;  //->this is ok when we "adding" two obj.
    }
};


but when i do the same "overload" outside the class,like:
1
2
int operator+(const obj x){
        return x;}// this is not okey when "adding" a number and a obj 


it seems that when we overloading operator"+" in class,the complier "helps" us to pass a "class" parameter to make that overloading works.

So now that i wonder whether complier do some work which is implicit to programmer or there is some implicit function are announced in a class.

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.



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.
i have soloved it,thans for your help
Topic archived. No new replies allowed.