1
#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

接下来是什么?复制发生在哪里 - Child 的 Parent 的复制构造函数?在返回 main ( ) 之前,所有控件都在哪里运行?

4

1 回答 1

2

由于您尚未定义任何自定义复制构造函数,因此编译器提供了一个默认构造函数。

默认的复制构造函数调用基类的复制构造函数,然后按成员进行复制

由于您的类没有数据成员,因此没有调用成员复制代码。

为了更好地研究和理解代码执行流程,您可能需要定义带有一些cout跟踪的自定义复制构造函数,例如:

class Parent 
{
public:
    ...

    Parent(const Parent& source)
    {
        std::cout << "Parent copy constructor" << std::endl;
    }
};

// ...similar for Child
于 2014-07-14T10:11:13.697 回答