64,282
社区成员
发帖
与我相关
我的任务
分享
#include<iostream>
using namespace std;
class Ratio{
friend ostream& operator<<(ostream&,const Ratio&);
private:
int num,den;
public:
Ratio(int n=1,int d=1):num(n),den(d){cout<<"Radio lives!"<<endl; };
Ratio(const Ratio& r):num(r.num),den(r.den),id(r.id){cout<<"Copy!"<<endl; };
~Ratio(){cout<<"Radio dies!"<<endl; };
Ratio& operator=(const Ratio&);
Ratio& operator++();
Ratio operator++(int);
};
Ratio& Ratio::operator ++(){
num+=den;
return *this;
}
Ratio Ratio::operator ++(int i){
Ratio temp=*this;
num+=den;
return temp;
}
Ratio& Ratio:: operator=(const Ratio& r){
num=r.num;
den=r.den;
cout<<"Overwrite = !"<<endl;
return *this;
}
ostream& operator<<(ostream& o,const Ratio& r){
o<<r.num<<"/"<<r.den;
return o;
}
void main(){
Ratio one(1,2);
Ratio three=one;
Ratio y=one;
cout<<y++<<endl;
y++=three;
cout<<y<<endl;
}
cout<<y++<<endl;
y++=three;
y++=three;
实际上是:
y.operator ++(0).operator=(three);
很明显要先调用operator++(int),然后再调用 operator=(Ratio const &)。three被赋值给y.operator++(int)的返回值,这是一个临时对象,在这条语句结束后,这个临时对象就被释放了。因此这个赋值其实 是个无效操作。
Ratio Ratio::operator ++(int i){
Ratio temp=*this;//第一次copy:拷贝构造temp
num+=den;
return temp;//第二次copy:拷贝构造临时对象
}//第一次die:释放temp;
.....
cout<<y++<<endl;
//第二次die:释放临时对象。