c++ - 如何在 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,在构造函数中逐个字段分配值,使用结构的默认复制构造函数进行分配,等等。我不知道在这种情况下哪种方式被认为是“最正确的”。
解决方案
推荐阅读
- json - 使用 Vue JS 从 API 中获取数据时遇到问题
- r - 排列 R 闪亮的侧边栏对象
- xamarin.android - 安装 Microsoft.Azure.Mobile.Client NuGet 包后生成错误
- java - 监控方法统计
- javascript - 在第一次渲染时获取 cookie 返回 undefined with universal-cookie
- c# - C#:类中实例的存储;尝试获取其价值时获取 NullReferenceException
- api - 如何为 Postman 集合中的每次迭代参数化测试?
- excel - 如何使用vba更改数据透视表中计算字段的名称
- java - 用于记录的动态实体拾取
- javascript - IE 中容器的奇怪行为