C++11 统一初始化(即列表初始化)不使用继承进行编译
C++11 Uniform initialization (i.e. list initialization) doesn't compile with inheritance
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;
};
相关文章:
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 为什么除了继承聚合结构之外,结构为空,无法聚合初始化?
- 初始化依赖于子类的继承类的常量类成员
- C++ 初始化继承的模板基类
- 使用继承初始化C++中的参数
- 我是否需要在虚拟继承类的构造函数中初始化基类以解决菱形继承问题?
- 继承的构造函数忽略类内初始化
- 是否可以在不修改父类的情况下将成员变量初始化推迟到继承的类?
- 跨继承树初始化元组
- 与lambda一起使用虚拟继承在初始化列表中捕获此问题的GCC错误
- GCC:当层次结构中存在虚拟继承时,C++11 内联对象初始化(使用 "this")不起作用
- 如何在派生类中初始化继承的模板POD结构
- 我如何避免明确构建C 初始化列表中继承的所有内容
- 使用从另一个类继承的类的对象初始化成员对象
- 正确的语法,用于在C 中继承,并具有初始化列表和内存分配
- 构造函数继承和直接成员初始化
- 继承构造函数不允许类似数组的初始化
- valgrind 在使用 std::make_shared 和虚拟继承时报告的未初始化值
- 初始化继承的成员数据
- 如何初始化继承类的静态变量