一.问题描述
pta多态实验:
1.定义一个整数加法器类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 n=0); Adder(Adder &p); void setNum(int x); int getNum()const; Adder operator+(const Adder &c)const; Adder operator++ (int); Adder& operator++(); void show()const; ~Adder(); }; Adder::Adder(int n):num(n) { cout<<"Adder Constructor run"<<endl; } Adder::Adder(Adder &p) { this->num=p.getNum(); cout<<"Adder CopyConstructor run"<<endl; } void Adder::setNum(int x) { num=x; } int Adder::getNum() const { return num; } Adder Adder::operator+(const Adder &c)const { return Adder(this->num+c.getNum()); } Adder& Adder::operator++() { num++; return *this; } Adder Adder::operator++(int) { Adder m=*this; ++(*this); return m; } void Adder::show()const { cout<<"Adder("<<num<<")"<<endl; } Adder::~Adder() { cout<<"Adder Destructor run"<<endl; }标签:const,show,int,每日,第十七,++,Adder,operator,打卡 From: https://www.cnblogs.com/zhenaifen/p/17357065.html