【问题标题】:C++ init class members constructorC++初始化类成员构造函数
【发布时间】:2015-09-15 19:55:29
【问题描述】:

我有两个班级,FooBarBar 包含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


【解决方案1】:

您可以使用委托构造函数(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.
        }
};

【讨论】:

    【解决方案2】:

    如果可以计算出必要的参数,那么您可以使用辅助函数:

    class Bar
    {
        static int ComputeFooArg() { /* ... */ };
    
    public:
        Bar(const char * filename) : FooInstance(ComputeFooArg())
        {
            // ...
        }
    
        // ...
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多