为什么+运算符重载返回类型是类类型而不是整数

Why does + operator overloading return type is class type not integer?

本文关键字:类型 整数 为什么 运算符 重载 返回类型      更新时间:2023-10-16

在本文中,作者选择返回类型为class类型http://www.learncpp.com/cpp-tutorial/92-overloading-the-arithmetic-operators/强调text,我们可以把返回类型改为return int吗,因为我想做下面的事情,我试过了,效果很好,为什么作者要把返回类型类改成??

#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;
}

除了许多其他事情之外,需要记住的一件事是,在同一类型的两个对象之间进行加法运算的结果总是非常特定的类型。所以它可能对你有用,但从逻辑上讲是不正确的。其次,如果不返回类类型,则无法执行嵌套的+语句。例如,如果你想这样做。

Obj1 + Obj2 + Obj3 ;

你会得到一个编译时错误。原因是+运算符的重载函数应该按相同类类型的值返回结果。下面编写的运算符也可以为函数调用编写,如下所示。

Obj1 + Obj2 ;

相当于…

Obj1.operator+(Obj2) ;

对于嵌套添加操作,您可以这样做。

Obj1 + Obj2 + Obj3 ;

相当于

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

这里,这部分。。。

(Obj1.operator+(Obj2))

成为另一个临时类对象,在该对象上以Obj3作为参数调用下一个方法。因此,如果您不从+函数返回类对象,那么这部分将是int,而不是对象。+函数不会在该int或任何其他非类数据类型上被调用。所以它会给你一个错误。

简而言之,建议始终通过重载的+函数的Value返回对象。

通常,加法的语义是,当您添加两个给定类型的对象时,您希望得到的对象具有相同的类型。

没有理由不能做你想做的事情,但它是非标准加法语义的一个例子。