【发布时间】:2015-09-15 19:55:29
【问题描述】:
我有两个班级,Foo 和 Bar。 Bar 包含Foo 的一个实例,需要用文件中的一些数据对其进行初始化。初始化列表不应该是好的,因为在初始化时计算机还不知道分配给Foo 的值。
class Foo {
int x;
public:
Foo(int new_x) : x(new_x) {}
};
class Bar {
Foo FooInstance;
public:
Bar(const char * fileneme)
/* Auto calls FooInstance() constructor, which does not exist
Shoild I declare it to only avoid this error? */
{
/* [...] reading some data from the file */
// Init a new FooInstance calling FooInstance(int)
FooInstance = Foo(arg);
/* Continue reading the file [...] */
}
};
创建一个新对象,对其进行初始化,然后将其复制到FooInstance 中是一个不错的选择,如源代码所示?
或者也许将FooInstance 声明为原始指针,然后用new 初始化它? (并在Bar析构函数中销毁它)
初始化FooInstance 最优雅的方式是什么?
【问题讨论】:
-
我要么让
FooInstance能够采用具有Initialization()类方法的默认构造函数,该类方法可以在 Bar 构造函数中调用,或者使其成为指针并使用 @ 创建它987654333@ 和 Bar 构造函数中的相应数据。在外部创建并复制它通常很难遵循和草率,尽管显然所有规则都有例外。
标签: c++ class constructor initialization