iam*_*ind -1 c++ inheritance compiler-errors c++11 list-initialization
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)
}
Run Code Online (Sandbox Code Playgroud)
上面的代码没有编译,并给出:
error: could not convert ‘{1}’ from ‘<brace-enclosed initializer list>’ to ‘D’
Run Code Online (Sandbox Code Playgroud)
即使我删除了"构造函数"行也是如此.如果我删除=符号,即D obj {1};它然后给出如下:
error: no matching function for call to ‘D::D(<brace-enclosed initializer list>)’
Run Code Online (Sandbox Code Playgroud)
解决此类问题的正确语法是什么?
D没有构造函数int.如果你想让它继承B构造函数,就这样说,像这样:
struct D : B {
using B::B;
int d;
};
Run Code Online (Sandbox Code Playgroud)
你可能想要做更多的事情,因为D有另一个int成员.
更完整的D两个B::b(通过调用B::B)初始化,D::d可能看起来像这样:
struct D : B {
D(int d_) : B(d_), d(d_) {}
int d;
};
Run Code Online (Sandbox Code Playgroud)
无论哪种方式,您的代码需要说D有一个构造函数int.
使用您的代码和我的代码链接到工作示例:http://goo.gl/YbSSHn