2021年2月22日月曜日、天気は良いです[過去を嘆いたり、現在を無駄にしたり、未来を恐れたりしないでください]
MyIntクラスを使用して、++ iおよびi ++を実装します。
class MyInt{
public:
int value; //实际的value值
MyInt(int value){
//方便初始化:MyInt i = 0;
this->value = value;
}
/**
* 重写前置式++运算符(++i时会自动调用本函数)
* @return 前置式运算会返回当前对象的引用
*/
MyInt& operator++(){
*this += 1; //自加1
return *this;
}
/**
* 重写后置式++运算符(i++时会自动调用本函数)
* 注意:由于函数重载是以参数类型来区分的,而前置、后置运算又都没有参数。为了解决这个语言学上的漏洞,
* 只好让后置式运算符有一个int类型的参数(调用时,编译器会默默地为这个int型参数指定0值)
* @return 返回一个const类型的对象
*/
const MyInt operator++(int){
MyInt oldValue = *this; //取出当前对象
++(*this); //累加(调用上面的前置++的重载函数)
return oldValue; //返回先前被取出的值
}
/**
* 重载运算符+=,方便赋值操作:*this += 1;
*/
MyInt& operator+=(int value){
this->value = this->value + value;
return *this;
}
//MyInt& operator--(); //前置式--的实现与上面类似
//const MyInt operator--(int); //后置式--的实现与上面类似
};