在本文中作者选择返回类型为类类型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;
}