继承和重载默认构造函数
Inherit and overload default constructor
我一直在寻找这个,我很惊讶我没有找到任何东西。为什么我不能使用 using
声明继承基础 class 构造函数并在派生的 class 中添加重载?我正在使用 Visual C++ 2013,当默认构造 b
:
时,基础 class 构造函数被忽略
error C2512: 'B' : no appropriate default constructor available
我已经通过重新定义构造函数来解决这个问题,但我不喜欢这样。这只是一个最小的例子,如果我只有一个基础 class 构造函数,我也不会打扰。
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;
我一直在寻找这个,我很惊讶我没有找到任何东西。为什么我不能使用 using
声明继承基础 class 构造函数并在派生的 class 中添加重载?我正在使用 Visual C++ 2013,当默认构造 b
:
error C2512: 'B' : no appropriate default constructor available
我已经通过重新定义构造函数来解决这个问题,但我不喜欢这样。这只是一个最小的例子,如果我只有一个基础 class 构造函数,我也不会打扰。
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;