虚基类的构造函数参数

Constructor arguments for virtual base classes

本文关键字:参数 构造函数 基类      更新时间:2023-10-16

考虑以下代码:

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) {}
};