为什么+运算符重载返回类型是类类型而不是整数
Why does + operator overloading return type is class type not integer?
在本文中,作者选择返回类型为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返回对象。
通常,加法的语义是,当您添加两个给定类型的对象时,您希望得到的对象具有相同的类型。
没有理由不能做你想做的事情,但它是非标准加法语义的一个例子。
相关文章:
- 将超出范围的整数分配给有符号字符类型
- 当我输入字符类型的数字时,为什么我无法获得整数?
- 整数类型应该显式转换(例如"int"到"无符号")还是只会增加混乱?
- 在 c++ 中,能够将浮点类型加 1 的最大整数是多少?
- 为什么 Clang 和 GCC 中两个无符号整数之和的结果类型不同
- 比较两个整数在C++中与未知 int 类型的相等性
- 如何在不给它任何类型(如整数)的情况下定义某物?
- 通过编译时值推断整数的类型
- C++/错误:表达式必须具有整数或无作用域枚举类型
- 从双精度转换为整数的显式类型是否始终检查整数溢出?
- 有没有办法将字符类型转换为整数?
- C++,概念不适用于无符号整数作为结果类型?
- 如何将整数分配给 char 类型的变量
- 类型转换问题:返回为整数而不是浮点/类型
- 涉及旧式枚举和整数类型的重载解析
- 将字符串转换为整数类型T,检查是否存在溢出
- 如何判断 c++ 向量中的值类型(整数或双精度)?
- 在 C/C++ 中,混合类型整数数学所需的最小类型向上转换是多少?
- 如何将字节数组转换为整数类型(整数、长整型、短型等)"安眠安"?
- 我可以在C++中制作一个强类型整数吗?