简体   繁体   中英

How does operator overloading work in this case?

I get how this operator overloading works here in this code.....

class operatorOver {
public:
    int a, b, c;
};

operatorOver operator+(const operatorOver &a, const operatorOver &b) {
    operatorOver aa;
    aa.a = b.a + a.a;
    return aa;
}

int main()
{
    operatorOver aaa, bbb, ccc;

    aaa.a = 100;
    bbb.a = 200;
    ccc = aaa + bbb;

    cout << ccc.a << endl;

    system("pause");
};

but this version I don't understand how this one works here....

class operatorOver {
public:
    operatorOver operator+(const operatorOver &a) {
        operatorOver aa;
        aa.a = (*this).a + a.a;
        return aa;
    }

    int a, b, c;
};

int main()
{
    operatorOver aaa, bbb, ccc;

    aaa.a = 100;
    bbb.a = 200;
    ccc = aaa + bbb;

    cout << ccc.a << endl;

    system("pause");
};

the 1st one I showed, I'm assuming the code of the operator overloading here is taking into 2 object classes in order for it to work...

but how come the 2nd example it's showing that I don't need to create another object class in it's parameters but still work... when you look in main() you see that there are 2 object classes still being passed in.... I'm lost.

In the second example, two object are passed. There's a and there is also this . The object passed as this is the left side of the operation.

Also note that your member operator+ should be const, since it doesn't mutate any data members of this .

Your member operator also invoke undefined behavior, since you are using a unassigned value:

// The member function
operatorOver operator+(const operatorOver &a) {
    operatorOver aa;

    // What is the value of aa.a? Undefined behavior!
    aa.a = aa.a + a.a;
    return aa;
}

To be equivalent to you non-member function, it should be this implementation:

// The member function
operatorOver operator+(const operatorOver &a) const {
    operatorOver aa;

    // Member `a`, could be written `this->a`
    aa.a = a + a.a;
    return aa;
}

Some of the binary operators, such as + , can be overloaded as member functions as well as non-member functions.

When + is overloaded as a member function, the function needs to be declared with one argument. When the operator is used as:

a + b

the call is resolved as

a.operator+(b);

When it is overloaded as a non-member function, the function needs to be declared with two arguments. When the operator is used as:

a + b

the call is resolved as

operator+(a, b);

Further reading: http://en.cppreference.com/w/cpp/language/operators

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM