Why does + operator overloading return type is cla

2019-07-27 14:11发布

问题:

In this article the author chose the return type to be class type http://www.learncpp.com/cpp-tutorial/92-overloading-the-arithmetic-operators/emphasized text ,Can we just change the return type to return int, because i wanted to do the following , i tried this and it just worked fine , why did the author made the return type class ??

#include <cstdlib>
#include <iostream>
using namespace std;
class Cents // defining new class
{
    private:
    int m_Cents;
    int m_Cents2;
    public:
    Cents(int Cents=0, int Cents2=0) // default constructor
    { 
        m_Cents=Cents;
        m_Cents2=Cents2;
}
Cents(const Cents &c1) {m_Cents = c1.m_Cents;}
friend ostream& operator<<(ostream &out, Cents &c1); //Overloading << operator
friend int operator+(const Cents &c1, const Cents &c2); //Overloading + operator
};
ostream& operator<<(ostream &out, Cents &c1)
{
out << "(" << c1.m_Cents << " , " << c1.m_Cents2 << ")" << endl;
return out; 
}
int operator+(const Cents &c1, const Cents &c2)
{
return ((c1.m_Cents + c2.m_Cents) + (c1.m_Cents2 + c2.m_Cents2 ));
}
int main(int argc, char *argv[])
{
Cents cCents(5, 6);
Cents bCents;
bCents = cCents;
cout << bCents << endl;
Cents gCents(cCents + bCents, 3);
cout << gCents << endl;
system ("PAUSE");
return 0;
}

回答1:

Apart from many other things, one thing to remember is that the result of the addition taking place between two objects of the same type is always of that very specific type. So it might work for you but logically it is incorrect. Secondly, you are unable to perform nested + statements with not returning the class type. For example if you want to do this.

Obj1 + Obj2 + Obj3 ;

You would get a compile time error. The reason is that the overloaded function for + operator should return the result by value of the same class type. The operators written below could also be written for the function call as follows.

Obj1 + Obj2 ;

is equivalent to...

Obj1.operator+(Obj2) ;

For the nested addition operation, you do this way.

Obj1 + Obj2 + Obj3 ;

which is equivalent to....

(Obj1.operator+(Obj2)).operator+(Obj3) ;
|---------------------|                       

Here, this part...

(Obj1.operator+(Obj2))

becomes another temporary class object on which the next method gets called with Obj3 as a parameter. So if you do not return class object from + function, this part would be an int instead of an object. The + function would not get called on that int or any other non-class data type. So it would give you an error.

In a nutshell, it is advisable to always return an object by Value, from overloaded + function.



回答2:

In general, the semantics of addition are that when you add two objects of a given type, you expect the resultant object to have the same type.

There's no reason you can't do what you want to do, but it is an example of nonstandard addition semantics.