您的位置:首页 > 编程语言 > C语言/C++

【C++】基类与子类拷贝构造函数的调用顺序

2015-11-17 09:02 253 查看
先看一段代码:

#include <iostream>

using namespace std;

class Base

{

public:

    Base()

    {

        cout<<"Base()\n";

        m_a=0;

    }

    Base(const Base& obj)

    {

        cout<<"Base(const Base& )\n";

        m_a=1;

    }

    int m_a;

};

class Derive : public Base

{

public:

    Derive()

    {

        cout<<"Derived()\n";

        m_b=0;

    }

  Derive(const Derive& obj):Base(obj)

    {

        cout<<"Derive(const Derive& )\n";

        m_b=1;

    }

    int m_b;

};

int main(int argc, char *argv[])

{

    Base base;

    Derive derive1;

    Derive derive2(derive1);

    system("pause");

    return 0;

}

运行结果如下:



由此可见,在调用子类拷贝构造函数时(注意:Base(obj)),先调用了父类的拷贝构造函数,对子类中父类的数据进行拷贝。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息