定义一个整数加法器类Adder,对其重载运算符“+”、“++”,main(void)函数完成对其的测试。

#include <iostream> using namespace std; /*请在这里填写答案*/ //主函数 int main(void){ int x; Adder a1,a2(a1); cin>>x; (a1++).show(); a1.show(); a2.setNum(x); (++a2).show(); a2.show(); (a1+a2).show(); return 0; }

答案:

class Adder
{
    int num;
public:
    Adder(int a = 0)
    {
        num = a;
        cout << "Adder Constructor run" << endl;
    }
    Adder(const Adder & c)
    {
        num = c.num;
        cout << "Adder CopyConstructor run" << endl;
    }
    ~Adder()
    {
        cout << "Adder Destructor run" << endl;
    }
    void setNum(int n)
    {
        num = n;
    }
    int getNum() const
    {
        return num;
    }
    Adder operator+(Adder & n)
    {
        Adder c;
        c.num = num + n.num;
        return c;
    }
    Adder & operator++()  //++a
    {
        ++num;
        return *this;
    }
    Adder operator++(int)  //a++
    {
        Adder b(*this);
        //b.num = num;
        ++num;
        return b;
    }
    void show() const
    {
        cout << "Adder" << "(" << num << ")" << endl;
    }
};