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

次は何?コピーはどこで行われますか - 親の子のコピーコンストラクター? メイン ( ) に戻る前に、コントロールはどこに移動しますか?

4

1 に答える 1

2

カスタム コピー コンストラクターを定義していないため、コンパイラによって既定のコンストラクターが提供されます。

既定のコピー コンストラクターは、基本クラスのコピー コンストラクターを呼び出してから、メンバーごとの copy を実行します。

クラスにはデータ メンバーがないため、呼び出されるメンバー コピー コードはありません。

コード実行の流れをよりよく調べて理解するために、いくつかのcoutトレースを使用してカスタム コピー コンストラクターを定義することができます。

class Parent 
{
public:
    ...

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

// ...similar for Child
于 2014-07-14T10:11:13.697 に答える