1

考虑以下代码:

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 一起使用吗?我是否可以假设通过多个父级间接继承虚拟基类的类总是必须直接显式调用基类的构造函数?

4

1 回答 1

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) {}
};
于 2015-10-16T15:17:55.617 回答