![]() |
#2
wanghui7372013-06-27 21:48
|

class num
{
public:
num()={n=new int;*n=1;cout<<"构造函数执行\n";}
~num(){delete n;n=NULL;cout<<析构函数执行\n";}
int get(){return *n;}
void set(int x){*n=x;}
num operator=(const num&r)
{ cout<<“operator=函数在调用\n";
*n=r.get();
return *this;
}
private:
int *n;
}
int main()
{
num one,two;
one.set(1);
num three;
three=two=one;
cout<<two.get();
return 0;
}
运行结果输出的two.get()的值是个随机数,而不是1,
为什么主函数中 执行 two=one;就可以使two.get()的值为1,而执行three=two=one;就出问题呢?问题出在哪里,请帮详细解释下,小弟是个新手,谢谢了
{
public:
num()={n=new int;*n=1;cout<<"构造函数执行\n";}
~num(){delete n;n=NULL;cout<<析构函数执行\n";}
int get(){return *n;}
void set(int x){*n=x;}
num operator=(const num&r)
{ cout<<“operator=函数在调用\n";
*n=r.get();
return *this;
}
private:
int *n;
}
int main()
{
num one,two;
one.set(1);
num three;
three=two=one;
cout<<two.get();
return 0;
}
运行结果输出的two.get()的值是个随机数,而不是1,
为什么主函数中 执行 two=one;就可以使two.get()的值为1,而执行three=two=one;就出问题呢?问题出在哪里,请帮详细解释下,小弟是个新手,谢谢了