首页 > 解决方案 > 如何在 c++98 中初始化作为类成员的结构?

问题描述

该应用程序是用 C++98 编写的,我目前无法更改它。情况是这样的:

struct foo
{
    int x;
    int y;
    int z;
}

class myClass
{
    public:
        myClass();
        struct foo bar;
        int baz;
};


myClass::myClass() :
bar({0}),
baz(0)
{
    //something else.
}


int main(int argc, char** argv)
{
    myClass* thing = new myClass();
    cout << thing.bar.z << endl;  //want a guaranteed zero here.
}

以上工作,但产生:

 warning: extended initializer lists only available with -std=c++11 or -std=gnu++11.

这是完全可以预料的。我不能bar({0})在初始化列表中使用 c++98。问题仍然是什么是正确的方法。

我可以想到几种可行的方法-memset,在构造函数中逐个字段分配值,使用结构的默认复制构造函数进行分配,等等。我不知道在这种情况下哪种方式被认为是“最正确的”。

标签: c++structconstructorc++98

解决方案


推荐阅读