#include <iostream> using namespace std; class num{ public: num(){n=new int;*n=1;cout<<"construct:"<<endl;} num(int x){n=new int;*n=x;cout<<"construct:"<<endl;} ~num(){delete n;n=NULL; cout<<"destruct:"<<endl;} //num(num &a){this->x=a.x;cout<<"copy:"<<x<<endl;} int getX(){ return *n; } void setX(int x) { *n=x; } num operator=(num &r){ cout<<"operator+"<<endl; *n=r.getX(); return *this; //返回two的副本,two的副本返回后进行析构,导致n指向的内存释放 } private: int *n; }; int & test(int & x) { cout<<x<<endl; return x; } int main() { num one,two,three; one.setX(110); two=one; //<==> two.operator =(one); cout<<two.getX()<<endl; return 0; }
时间: 2024-10-09 17:32:53