c++ - 什么没有继承到 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=、默认构造函数和复制构造函数?
解决方案
Dervied 没有构造函数,在这种情况下,会生成一个默认构造函数,它调用所有基类和成员的默认构造函数。
复制构造函数和赋值运算符也会发生类似的事情。基类版本由自动生成的派生类版本调用。
这与构造函数或赋值运算符的继承无关。
推荐阅读
- javascript - 只允许 td 中的数字,其中 contenteditable = true
- node.js - 使用带有节点 js 的打字稿从弹性搜索中删除记录
- docker - 如何在基于 docker 的环境中创建 redis-cluster
- python - 从行中的多个值中计算一个值
- java - 如何在 Java 中将对象写入 JSON 文件?
- reactjs - 在 React Native 中使用视图/编辑模式的组件最明智的方法是什么?
- postgresql - plpgsql 函数 - 列名不明确
- javascript - Javascript 数组处理,Firefox 和 Chrome 的区别
- javascript - 有没有办法从 Html 中的输入中获取完整的文件路径?
- angular - 从子组件调用父函数