-1

我正在尝试 ISO 2011 sec 12.9 第 7 段中的示例。以下是我要编译的代码

int chk;
struct B1 {   B1(int){chk=9;} };
struct B2 {   B2(int){chk=10;} };
struct D2 : B1, B2 {
       using B1::B1;
       using B2::B2;
      D2(int){chk=0;};  
};
int main(){
  B1 b(9);
  D2 d(0);
  return 0;
}

$g++ -std=c++11 sample.cpp 错误信息

 <source>: In constructor 'D2::D2(int)': <source>:7:10: error: no matching function for call to 'B1::B1()'    D2(int){chk=0;};
      ^ <source>:2:15: note: candidate: B1::B1(int)  struct B1 {   B1(int){chk=9;} };
           ^~ <source>:2:15: note:   candidate expects 1 argument, 0 provided <source>:2:8: note: candidate: constexpr B1::B1(const B1&)  struct B1 {   B1(int){chk=9;} };
    ^~ <source>:2:8: note:   candidate expects 1 argument, 0 provided <source>:2:8: note: candidate: constexpr B1::B1(B1&&) <source>:2:8: note:   candidate expects 1 argument, 0 provided <source>:7:10: error: no matching function for call to 'B2::B2()'    D2(int){chk=0;};
      ^ <source>:3:15: note: candidate: B2::B2(int)  struct B2 {   B2(int){chk=10;} };
           ^~ <source>:3:15: note:   candidate expects 1 argument, 0 provided <source>:3:8: note: candidate: constexpr B2::B2(const B2&)  struct B2 {   B2(int){chk=10;} };
    ^~ <source>:3:8: note:   candidate expects 1 argument, 0 provided <source>:3:8: note: candidate: constexpr B2::B2(B2&&) <source>:3:8: note:   candidate expects 1 argument, 0 provided Compiler exited with result code 1

这是 gcc 中的错误吗?为什么要寻找 B1()?我使用的是 gcc 6.3.0

编辑:链接问题中的问题是关于何时使用一个基类。即以下代码

int chk;
struct B1 {   B1(int){chk=9;} };
//struct B2 {   B2(int){chk=10;} };
struct D2 : B1  {
   using B1::B1;
  //using B2::B2;
  //D2(int){chk=0;};  
 };
int main(){
   B1 b(9);
   D2 d(0);
   return 0;
}

哪个有效,但是当引入 D2(int){chk=0;} 时,就会发生错误。

4

1 回答 1

0

D中,您提供了唯一的构造函数D2(int){chk=0;},它不会显式调用基类的任何构造函数,B1并且B2. B1因此,编译器在and中查找默认构造函数B2,该构造函数将被隐式调用。但是您的基本结构B1B2没有提供默认构造函数...

B1因此,要么在and中定义默认构造函数,要么在B2构造函数的初始化列表中显式调用其他构造D函数:

D2(int x):B1(x),B2(x) {chk=0;};
于 2017-05-01T21:30:40.637 回答