每日打卡一小时(第十七天)

一.问题描述

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);
    Adder(Adder&&); 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; }
 
posted @ 2023-04-26 19:28  伐木工熊大  阅读(22)  评论(0)    收藏  举报