Amj*_*kir 1 c++ operator-overloading
在本文中,作者选择返回类型为类类型http://www.learncpp.com/cpp-tutorial/92-overloading-the-arithmetic-operators/ 强调文本,我们只需将返回类型更改为返回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;
}
Run Code Online (Sandbox Code Playgroud)
Cod*_*ash 10
除了许多其他事情之外,要记住的一件事是在相同类型的两个对象之间进行添加的结果始终是非常特定的类型.所以它可能适合你,但逻辑上它是不正确的.其次,您无法在+不返回类类型的情况下执行嵌套语句.例如,如果你想这样做.
Obj1 + Obj2 + Obj3 ;
Run Code Online (Sandbox Code Playgroud)
您将收到编译时错误.原因是+运算符的重载函数应该返回相同类类型的值的结果.下面写的运算符也可以为函数调用编写如下.
Obj1 + Obj2 ;
Run Code Online (Sandbox Code Playgroud)
相当于......
Obj1.operator+(Obj2) ;
Run Code Online (Sandbox Code Playgroud)
对于嵌套的加法操作,您可以这样做.
Obj1 + Obj2 + Obj3 ;
Run Code Online (Sandbox Code Playgroud)
这相当于....
(Obj1.operator+(Obj2)).operator+(Obj3) ;
|---------------------|
Run Code Online (Sandbox Code Playgroud)
在这里,这部分......
(Obj1.operator+(Obj2))
Run Code Online (Sandbox Code Playgroud)
成为另一个临时类对象,下一个方法Obj3作为参数被调用.因此,如果您不从+函数返回类对象,则此部分将是int一个对象而不是对象.+不会在该int或任何其他非类数据类型上调用该函数.所以它会给你一个错误.
简而言之,建议始终通过Value从重载+函数返回一个对象.