繁体   English   中英

通过复制派生类的另一个对象来创建派生类的对象时,调用基类的副本构造函数

[英]Calling copy constructor of base class while creating object of derive class by copying another object of derive class

class base {};
class der : public base{};


der d1;
der d2(d1);

该语句调用类库的默认构造函数,然后复制claas der的构造函数。 我的问题是,为什么C ++在通过复制派生类的另一个对象创建派生类的对象时没有提供调用基类的副本构造函数的功能

简洁版本

该语句调用类库的默认构造函数,然后复制claas der的构造函数。

不,不是。

我的问题是,为什么C ++在通过复制派生类的另一个对象创建派生类的对象时没有提供调用基类的副本构造函数的功能

是的


加长版

我不知道您是如何得出结论的,即在构造d2调用了基本默认构造函数,但事实并非如此。 该合成基础拷贝构造函数调用,如您所愿。

真的很容易测试

struct base {
   base() { cout << "*B"; }
   base(base const& b) { cout << "!B"; }
  ~base() { cout << "~B"; }
};

struct der : base {};

int main() {
   der d1;
   der d2(d1);
}

// Output: *B!B~B~B

派生类的复制构造函数调用基类的默认构造函数。

下面的示例程序进行了演示。

#include <iostream>

using namespace std;

class Base
{
public:
    Base(){ cout<<"Base"<<endl; }
    Base(int i){ cout<<"Base int "<<endl; }
    Base(const Base& obj){ cout<<"Base CC"<<endl; }
};

class Derv : public Base
{
public:
    Derv(){ cout<<"Derv"<<endl; }
    Derv(int i){ cout<<"Derv int "<<endl; }
    Derv(const Derv& obj){ cout<<"Derv CC"<<endl; }
};

int main()
{
    Derv d1 = 2;
    Derv d2 = d1; // Calls the copy constructor

    return 0;
}

该语句调用类库的默认构造函数,然后复制claas der的构造函数。

不,不是的。

第一行调用der类的默认构造,而der调用类base的默认构造函数。 第二行调用der类的copy构造函数,因为您要将一个der实例复制到另一个实例。

编译器生成的copy-constructor将调用基类的copy构造函数。

您可能已经为der添加了用户定义的副本构造函数。 在这种情况下,必须显式调用基类的副本构造函数。

der::der(const der& other): base(other), ... {}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM