在这篇文章中笔者选择了返回类型为类类型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;
}