#include<iostream>
using namespace std;
class Parent
{
public:
Parent ( )
{
cout << "P";
}
};
class Child : public Parent
{
public:
Child ( )
{
cout << "C";
}
};
int main ( )
{
Child obj1;
Child obj2 ( obj1 );
return 0;
}
程序如下:
=> An object of the class 'Child' named 'obj1' is created
=> Call to the constructor of the 'Child' class is made
=> Call to the constructor of the 'Parent' class is made
=> "P" is printed
=> Control transferred back to 'Child ( )'
=> "C" is printed
=> An object 'obj2' of the class 'Child' is created as a copy of 'obj1'
=> Call to the copy constructor of the 'Child' class is made
=> Call to the copy constructor of the 'Parent' class is made
下一个什么?复制发生在哪里——父节点的复制构造函数还是子节点的复制构造函数?在返回到main()之前,所有的控制都在哪里?
由于没有定义任何自定义复制构造函数,编译器提供了一个默认的。
默认复制构造函数调用基类的复制构造函数,然后按成员复制。
因为你的类没有数据成员,所以没有成员复制代码被调用。
为了更好地研究和理解代码执行的流程,你可能想要定义带有cout
跟踪的自定义复制构造函数,例如:
class Parent
{
public:
...
Parent(const Parent& source)
{
std::cout << "Parent copy constructor" << std::endl;
}
};
// ...similar for Child