#include <iostream>
using namespace std;
class Adder
{
private:
int num;
public:
Adder(int n=0);//有参构造函数,其中参数默认值为0
Adder(const Adder &adder);//拷贝构造函数
~Adder();//析构函数
void setNum(int n);//公有函数,用于设置数值域
int getNum() const;//公有函数,用于返回数值域
Adder operator+(Adder &a);//重载+运算符
Adder& operator++(void);//前置++运算符重载
const Adder operator++(int);//后置++运算符重载
void show() const;//显示
};
Adder::Adder(int n)//有参构造函数的实现
{
num=n;
cout<<"Adder Constructor run"<<endl;
}
Adder::Adder(const Adder &adder)//拷贝构造函数的实现
{
num = adder.num;
cout<<"Adder CopyConstructor run"<<endl;
}
Adder::~Adder()//析构函数的实现
{
cout<<"Adder Destructor run"<<endl;
}
void Adder::setNum(int n)
{
num=n;
}
int Adder::getNum()const
{
return num;
}
Adder Adder::operator+(Adder &a)//重载+运算符
{
this->num = this->num + a.num;
return (Adder(getNum()));
}
Adder& Adder::operator++(void)//前置重载++运算符
{
num++;
return *this;
}
const Adder Adder::operator++(int)//后置重载++运算符
{
Adder ad=*this;
++(*this);
return ad;
}
void Adder::show()const
{
cout<<"Adder("<<num<<")"<<endl;
}
//主函数
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;
}
|