C++11 统一初始化(即列表初始化)不使用继承进行编译

C++11 Uniform initialization (i.e. list initialization) doesn't compile with inheritance

本文关键字:初始化 继承 编译 列表 C++11      更新时间:2023-10-16
struct B { 
  int b; 
  B(int i = 0) : b(i) {};  // constructor
};
struct D : B  {
  int d;
};
int main () {
  D obj = {1};  // <-- error
  // D obj {1}; // <-- error (different)
}

上面的代码不能编译,并给出:

error: could not convert ‘{1}’ from ‘<brace-enclosed initializer list>’ to ‘D’

同样如此,即使我删除了"构造函数"行。如果我去掉=符号,即D obj {1};,那么它给出如下:

error: no matching function for call to ‘D::D(<brace-enclosed initializer list>)’

解决这个问题的正确语法是什么?

D没有接受int的构造函数。如果您希望它继承B的构造函数,就像这样说:

struct D : B  {
  using B::B;
  int d;
};

考虑到D有另一个int成员,您可能想要做的不止这些。

一个更完整的D,它初始化B::b(通过调用B::B)和D::d,可能看起来像这样:

struct D : B  {
  D(int d_) : B(d_), d(d_) {}
  int d;
};

无论哪种方式,您的代码都需要说明D有一个接受int的构造函数。

链接到使用您的代码和我的代码片段的工作示例:http://goo.gl/YbSSHn

在你写的D只有一个默认构造函数,不知道如何调用B::B(int i)。您所要做的就是在D中提供一个相应的构造函数,如:

struct D : B  {
  D(int i) : B(i) {}//;
  int d;
};