拷贝构造函数被调用的三种情况
定义一个Complex类
class Complex {
pulic
:
double real
, image
;
Complex(){}
Complex(const Complex
&c
) {
real
= c
.real
;
imag
= c
.image
;
cout
<< "Copy Constructor called";
}
};
1.当用一个对象去初始化同类的另一个对象时
Complex c1
;
Complex
c2(c1
);
Complex c2
= c1
;
2.如果某函数有一个参数是类A的对象,那么该函数被调用时,类A的赋值构造函数将被调用
void Func(Complex a1
){}
int main() {
Complex a2
;
Func(a2
);
return 0;
}
a1的值未必等于a2,具体看拷贝构造函数的内容(有没有赋值)。 3.如果函数的返回值是类A的对象时,则函数返回时,A的拷贝构造函数将被调用
Complex
Func() {
Comeplex b
;
b
.real
= 1;
b
.image
= 1;
return b
;
}
int main() {
cout
<< Func().real
<< endl
;
return 0;
}
返回的值未必相等,取决于拷贝构造函数中是否进行了赋值操作。