#include<iostream>
#include<iomanip>
#include<string>
using namespace std;
class Myclass{
public:
Myclass (int *p);
~Myclass();
Myclass & operator=(const Myclass &rhs);
void print();
private:
int *ptr;
};
Myclass::Myclass(int *p){
ptr=p;
}
Myclass::~Myclass(){
delete ptr;
}
Myclass &Myclass::operator=(const Myclass &rhs){
if(this!=&rhs){ //a=b;
delete ptr;
ptr=new int;
*ptr=*rhsNaNr; //*ptr=(*rhs)NaNr; is wrong:“=” 无法从“*const ”转换为“int”
}else{
cout<<"two sides of = is the same!"<<endl;
}
return *this;
}
void Myclass::print(){
cout<<*ptr<<endl;
}
int main(){
Myclass pa(new int (1)),pb(new int (3));
pa.print();
pb.print();
cout<<"change result :\n";
pb=pa; //Myclass pc=pa; is wrong
pa.print();
pb.print();
return 0;
}
转载于:https://my.oschina.net/u/2264568/blog/344957