首页 > > > C++类的拷贝构造函数什么时候被调用?
#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.该程序中的拷贝构造函数在不同的时刻被调用了三次,为什么会成这种情况,我主要想问拷贝构造函数什么时候被调用?
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4547/viewspace-3118355/ ,如需转载,请注明出处,否则将追究法律责任。