首页 > 解决方案 > 什么没有继承到 C++ 派生类?显然, operator= 和一些构造函数实际上是继承的

问题描述

我正在尝试学习 C++ 继承,但有一件事对我来说没有任何意义。所有关于派生类没有继承的东西的谷歌搜索都说构造函数、朋友和 operator= 没有被继承。但是,此信息不符合我的程序的结果。

我做了一个继承的例子,结果如下:

#include <iostream>
using namespace std;

class Base
{
public:
  Base()
  {
    cout << "constructor base class without parameters" << endl;
  }

  Base(int a)
  {
    cout << "constructor base class with int parameter" << endl;
  }

  Base(const Base& b)
  {
    cout << "copy constructor base class" << endl;
  }

  Base& operator= (const Base& base)
  {
    cout << "operator= base class" << endl;
  }
};

class Derived: public Base
{
};

int main()
{
  Derived d;

  cout << endl << "here 1" << endl << endl;

  Derived d2 = d;

  cout << endl << "here 2" << endl << endl;

  d = d2;

  //Derived d3 (3); // ERROR!!
}

输出是:

constructor base class without parameters                                                                                                           

here 1                                                                                                                                              

copy constructor base class

here 2                                                                                                                                              

operator= base class

如果所有的构造函数和operator=都没有被继承,为什么要调用基类的operator=、默认构造函数和复制构造函数?

标签: c++c++11inheritanceconstructor

解决方案


Dervied 没有构造函数,在这种情况下,会生成一个默认构造函数,它调用所有基类和成员的默认构造函数。

复制构造函数和赋值运算符也会发生类似的事情。基类版本由自动生成的派生类版本调用。

这与构造函数或赋值运算符的继承无关。


推荐阅读