c++ - 继承和重载默认构造函数

标签 c++ class oop inheritance constructor

我一直在寻找这个,我很惊讶我什么也没找到。为什么我不能使用 using 声明继承基类构造函数并在派生类中添加重载?我正在使用 Visual C++ 2013,在默认构造 b 时忽略基类构造函数:

error C2512: 'B' : no appropriate default constructor available

我已经通过重新定义构造函数来解决这个问题,但我不喜欢这样。这只是一个最小的示例,如果我只有一个基类构造函数,我不会感到困扰。

struct A
{
    A() : a(10) {}

    int a;
};

struct B : A
{
    using A::A;

    explicit B(int a) { this->a = a; }
};

int main()
{
    B b;
}

最佳答案

问题是默认构造函数不是继承的。来自 [class.inhctor]/p3:

For each non-template constructor in the candidate set of inherited constructors [..], a constructor is implicitly declared with the same constructor characteristics unless there is a user-declared constructor with the same signature in the complete class where the using-declaration appears or the constructor would be a default, copy, or move constructor for that class.

您还有一个用户声明的构造函数,它禁止创建隐式默认构造函数。只需添加一个默认值即可使其工作:

B() = default;

关于c++ - 继承和重载默认构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34339641/

相关文章:

c++ - 类成员初始化的最佳实践

php - 如何调用分配给类变量的 PHP 闭包?

python - 如何在Python中将所有引用变量设置为None?

Delphi:写入后代类中私有(private)祖先的字段

c# - 如何正确使用依赖注入(inject)?

c++ - 填充 CUDA 内核中的数组或列表,但不是在每个线程中

c++ - transform() 需要多少个参数?

c++ - 从文件读取到不同的类对象

c++ - 如何声明模板类的模板

C++:ios::app 在 fstream 中不需要 ios::out