我有两个类,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
最优雅的方式是什么?
可以使用委托构造函数(c++ 11以后)和额外的函数:
MyDataFromFile ReadFile(const char* filename);
class Bar {
Foo FooInstance;
public:
Bar(const char* fileneme) : Bar(ReadFile(filename)) {}
private:
Bar(const MyDataFromFile& data) : FooInstance(data.ForFoo)
{
// other stuff with MyDataFromFile.
}
};
如果可以计算必要的参数,则可以使用辅助函数:
class Bar
{
static int ComputeFooArg() { /* ... */ };
public:
Bar(const char * filename) : FooInstance(ComputeFooArg())
{
// ...
}
// ...
};