【发布时间】:2015-10-16 14:20:50
【问题描述】:
考虑以下代码:
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 接受上述内容,但带有 -std=c++11 的 gcc 4.8 抱怨此代码:
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 一起使用吗?我是否可以假设通过多个父级间接继承虚拟基类的类总是必须直接显式调用基类的构造函数?
【问题讨论】:
-
“我是否可以假设通过多个父类间接继承虚拟基类的类总是必须直接显式调用基类的构造函数?”是的,如果它是某个对象的最派生类。因为虚基必须由最派生的类初始化。
-
代码在Visual C++ 2015下编译得很好。我看不出有什么问题,而且g++的错误信息中提到的原因也不成立。
标签: c++ constructor multiple-inheritance virtual-inheritance inherited-constructors