在link见到的一个问题
代码:
#include<iostream>
using namespace std;
class Complex
{
private:
double real;
double imag;
public:
Complex(double r=0,double i=0)
{
cout<<" constructing···\n";
real=r;
imag=i;
}
Complex(Complex &c)
{
cout<<"copy constructing···\n";
real=c.real;
imag=c.imag;
}
~Complex()
{
cout<<"destructing···\n";
}
double realcomplex()
{
return real;
}
double imagcomplex()
{
return imag;
}
};
void display(Complex p)
{
cout<<"The real of complex="<<p.realcomplex()<<endl;
cout<<"The imag of complex="<<p.imagcomplex()<<endl;
}
int main()
{
Complex a(1.1,2.2);
Complex b;
Complex c(a);
display(a);
display(b);
display(c);
return 0;
}
constructing···
constructing···
copy constructing···
copy constructing···
The real of complex=1.1
The imag of complex=2.2
destructing···
copy constructing···
The real of complex=0
The imag of complex=0
destructing···
copy constructing···
The real of complex=1.1
The imag of complex=2.2
destructing···
destructing···
destructing···
destructing···
Process returned 0 (0x0) execution time : 0.891 s
Press any key to continue.
该程序中的拷贝构造函数在不同的时刻被调用了三次,为什么会成这种情况,我主要想问拷贝构造函数什么时候被调用?
anwser:拷贝构造函数被执行了四次,而且一看楼主就不是纯粹的菜鸟。简单说一下,楼主应该就明白了。
第一次 Complex c(a); 执行了拷贝构造函数, a->c
第二次 display(a); 执行了拷贝构造函数 a->p(p就是void display(Complex p)中的p)
第三次 display(b); 执行了拷贝构造函数 b->p(p就是void display(Complex p)中的p)
第四次 display(c); 执行了拷贝构造函数 c->p(p就是void display(Complex p)中的p)
楼主应该清楚了吧。