我一直在寻找这个,我很惊讶我什么也没找到。为什么我不能使用 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/