【问题标题】:Calling base class' constructor without defining it in derived class [duplicate]调用基类的构造函数而不在派生类中定义它[重复]
【发布时间】:2021-11-09 08:57:23
【问题描述】:
class A {
public:
  int _a
  A(int a) : _a { a} { }
};

class B : public A { }

为什么不能使用继承的构造函数初始化A类型的变量?

B a(5);

错误:“'B' 的初始化没有匹配的构造函数”

【问题讨论】:

  • 记得指定虚拟析构函数或受保护的非虚拟析构函数。

标签: c++


【解决方案1】:

因为B 没有这样的构造函数默认采用int,除非inherit 明确表示:

class B : public A { 
    using A::A; // inheriting constructor
};

【讨论】:

  • 有没有办法让它隐式化,这样一个类的任何子类都将始终继承基类的构造函数而不使用using 指令?
  • @luis AFAIK,没有。
猜你喜欢
  • 1970-01-01
  • 2016-07-19
  • 1970-01-01
  • 2020-09-22
  • 2011-05-03
  • 2018-07-16
  • 2018-07-21
  • 2015-05-28
  • 2015-08-18
相关资源
最近更新 更多