请考虑以下代码:
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和-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一起使用?我是否正确地假设通过多个父节点间接继承虚拟基类的类总是必须明确地直接调用基类的构造函数?
答案 0 :(得分:2)
这是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) {}
};