无法构造对象,因为成员没有默认构造函数
Can't construct object because member doesn't have default constructor
编译我的程序时,出现此错误:
error: constructor for 'parser' must explicitly initialize the member 'lexer_inst' which does not have a default constructor
如错误所述,我的成员“lexer_inst”没有默认构造函数。但是,我不希望它首先是默认构造的。无论如何,我正在写信给构造函数中的成员。在我自己初始化之前,我无法让成员保持未初始化状态,这对我来说似乎是不合逻辑的。在我的例子中,我不能为我的成员使用初始化列表,因为它取决于在构造函数中创建的另一个成员的值。
这是我的构造函数代码:
parser::parser(source_file &file) : file(file) {
this->ast_arena = arena(file.data.length * 4);
this->lexer_inst = lexer(this->ast_arena, file);
}
如何保持“lexer_inst”未初始化? (它的类型是“lexer”,它实际上有引用成员,因此不能被默认初始化)
How can I keep "lexer_inst" uninitialized?
你不能,也不应该。将构造函数更改为
parser::parser(source_file& file)
: file(file)
, ast_arena(file.data.length * 4)
, lexer_inst(ast_arena, file) {}
也就是说,专门使用成员初始化列表来设置你的class,不要试图将这个初始化推入构造函数的主体。
确保您的成员声明顺序与初始化顺序一致,否则上述操作将失败。如果不是这样,好的编译器会警告你。
编译我的程序时,出现此错误:
error: constructor for 'parser' must explicitly initialize the member 'lexer_inst' which does not have a default constructor
如错误所述,我的成员“lexer_inst”没有默认构造函数。但是,我不希望它首先是默认构造的。无论如何,我正在写信给构造函数中的成员。在我自己初始化之前,我无法让成员保持未初始化状态,这对我来说似乎是不合逻辑的。在我的例子中,我不能为我的成员使用初始化列表,因为它取决于在构造函数中创建的另一个成员的值。
这是我的构造函数代码:
parser::parser(source_file &file) : file(file) {
this->ast_arena = arena(file.data.length * 4);
this->lexer_inst = lexer(this->ast_arena, file);
}
如何保持“lexer_inst”未初始化? (它的类型是“lexer”,它实际上有引用成员,因此不能被默认初始化)
How can I keep "lexer_inst" uninitialized?
你不能,也不应该。将构造函数更改为
parser::parser(source_file& file)
: file(file)
, ast_arena(file.data.length * 4)
, lexer_inst(ast_arena, file) {}
也就是说,专门使用成员初始化列表来设置你的class,不要试图将这个初始化推入构造函数的主体。
确保您的成员声明顺序与初始化顺序一致,否则上述操作将失败。如果不是这样,好的编译器会警告你。