虚基类的构造函数参数
Constructor arguments for virtual base classes
考虑以下代码:
class A {
int i;
public:
A(int index) : i(index) {}
int get() { return i; }
};
class B : virtual public A {
public:
using A::A;
};
class C : virtual public A {
public:
using A::A;
};
class D : public B, public C {
public:
D(int i) : A(i), B(i), C(i) {}
};
int main() {
D d(1);
return 0;
}
当clang 3.7接受以上代码时,gcc 4.8 with -std=c++11
抱怨这段代码:
In constructor 'D::D(int)':
20:29: error: use of deleted function 'B::B(int)'
D(int i) : A(i), B(i), C(i) {}
^
10:12: note: 'B::B(int)' is implicitly deleted because the default definition would be ill-formed:
using A::A;
^
10:12: error: no matching function for call to 'A::A()'
10:12: note: candidates are:
4:3: note: A::A(int)
A(int index) : i(index) {}
^
4:3: note: candidate expects 1 argument, 0 provided
1:7: note: constexpr A::A(const A&)
class A {
^
1:7: note: candidate expects 1 argument, 0 provided
1:7: note: constexpr A::A(A&&)
1:7: note: candidate expects 1 argument, 0 provided
20:29: error: use of deleted function 'C::C(int)'
D(int i) : A(i), B(i), C(i) {}
^
15:12: note: 'C::C(int)' is implicitly deleted because the default definition would be ill-formed:
using A::A;
^
15:12: error: no matching function for call to 'A::A()'
15:12: note: candidates are:
4:3: note: A::A(int)
A(int index) : i(index) {}
^
4:3: note: candidate expects 1 argument, 0 provided
1:7: note: constexpr A::A(const A&)
class A {
^
1:7: note: candidate expects 1 argument, 0 provided
1:7: note: constexpr A::A(A&&)
1:7: note: candidate expects 1 argument, 0 provided
我写的代码是否符合标准?这是实现我正在尝试的最好方法,即传递构造函数参数到多继承树到实际持有数据的公共基类?或者我能以某种方式简化它或使它与gcc一起工作吗?我是否可以假设通过多个父类间接继承虚拟基类的类总是必须直接显式调用基类的构造函数?
这是GCC错误58751。您的代码应该像在Clang中那样编译。在过去,GCC在继承带有虚拟继承的构造函数时遇到了一些问题。
一种解决方法是手动编写转发构造函数。
class B : virtual public A {
public:
B(int i) : A(i) {}
};
class C : virtual public A {
public:
C(int i) : A(i) {}
};
相关文章:
- C++:使用运算符 = 调用多参数构造函数
- 通过零参数构造函数创建的 glm::mat4 应该包含哪些值?
- 好奇的混合与可变参数构造函数
- 具有默认值的单个参数构造函数是否与默认构造函数相同?
- 为什么我们需要创建一个单参数构造函数来使用临时的无名称对象
- 在可变参数构造函数中初始化常量数组
- C++ 显式多参数构造函数歧义
- 零一参数构造函数
- 可变参数构造函数中的 SFINAE
- 当没有显式关键字与单参数构造函数一起使用时,编译器可以发出警告
- 可变参数类模板和可变参数构造函数
- 确保模板参数类型与其可变参数构造函数的类型匹配
- C++默认参数构造函数与内联初始化优先级
- 如何在 c++ 中将包含复制构造函数的类的参数构造函数称为私有?
- 自动存储中没有无参数构造函数的类对象和异常
- 警告:用两个参数构造函数返回对象时,表达结果未使用
- 如何在C++中调用无参数构造函数
- 在 c++ 中具有多个参数构造函数的模板类存在问题
- 可变参数构造函数优先于用户提供的移动构造函数,除非默认
- 如何从可变参数构造函数参数构造任何对象?