何时调用复制构造函数
1、按值传递对象
2、函数返回对象
3、复制初始化,即用一个对象初始化另一个对象
#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout << "constructor" << endl;
}
A(const A& a)
{
cout << "copy constructor" << endl;
}
~A()
{
cout << "destructor" << endl;
}
A* Clone()
{
return new A(*this);
}
protected:
private:
};
void test1() //复制初始化
{
A a;
A b = a;
}
void test2() //复制初始化
{
A a;
A *b = new A(a);
delete b;
}
void test3() //复制初始化
{
A *a = new A();
A b = *a;
delete a;
}
void test4() //复制初始化
{
A *a = new A();
A *b = new A(*a);
delete a;
delete b;
}
void test5(A a) //按值传递对象
{
}
void test6(const A& a) //传递对象的引用
{
}
A test7() //函数返回对象
{
A a;
return a;
}
int main()
{
cout << "test1:" << endl;
test1();
cout << "test2:" << endl;
test2();
cout << "test3:" << endl;
test3();
cout << "test4:" << endl;
test4();
A a;
cout << "test5:" << endl;
test5(a);
cout << "test6:" << endl;
test6(a);
cout << "test7:" << endl;
test7();
cout << "end test-------------------" << endl;
return 0;
}
输出结果为:

浙公网安备 33010602011771号