类型:转载 责任编辑:asp 日期:2007/03/01
下面这段代码很简单啊但是结果好奇怪,出现四次构造函数却出现五次析构函数!!!
请高手帮忙看看啊!!!!!
#include<iostream.h>
class complex
{
float real;
float image;
public:
complex(float r=0,float i=0)
{real=r;image=i;cout<<"calling constructor..."<<endl;}
~complex()
{cout<<"calling disconstructor..."<<endl;}
void show()
{cout<<"real:"<<real<<" "<<"image:"<<image<<endl;}
complex operator+(complex&c)
{
complex t;
t.real=real+c.real;
t.image=image+c.image;
return t;
}
};
void main()
{
complex c1(1,1);
c1.show();
complex c2;
c2.show();
c2=c1+(complex)3;
c2.show();
}
推荐阅读
你算上拷贝构造了么?
没算拷贝构造
你提供一个拷贝构造看看!
complex c1(1,1);
//1constructor
complex c2;
//1constructor
c2=c1+(complex)3;
//3 constructor:1个是(complex)3的,一个是operator+用到的t的,还有一个是=产生(他用了拷贝构造编译器产生的,所以没有信息显示,但destructor是你提供的,所以有信息显示,你可以提供一个copyconstructor来看看).
楼上说得对,你自己没写拷贝构造函数,所以有一次“地下”进行的构造你没看到。^o^
帮你些个拷贝构造函数吧,
complex::complex(const complex& c)
{
real = c.real;
image = c.image;
}