C++ 错误 - <unnamed-tag> 匿名 union 的成员不允许使用内置初始化程序

标签 c++ visual-studio-2013

我在这里的第一篇文章,在此先感谢。 我是 C++ 的新手,正在为这个错误而苦苦挣扎。

typedef struct {
    int x;
    int z;
    char ref[20]; // or of other adequate type
    DATE date;
    bool put;
    int hasPiece = false;

} TRequest;

当我构建它时,它会在标题中显示错误

"<unnamed-tag>::hasPiece' : an in-class initializer is not allowed for a member of an anonymous union in non-class scope.

你能帮帮我吗??非常感谢

最佳答案

在 c++98 中,您不允许为结构的成员提供默认值,但在以后的标准中您可能可以这样做。请改用这种方法:

struct TRequest 
{
    TRequest()
      : hasPiece(0)
    {
      // Nothing to do here
    }

    int x;
    int z;
    char ref[20]; // or of other adequate type
    DATE date;
    bool put;
    int hasPiece;
};

请注意,您也应该初始化所有其他成员,而不仅仅是 hasPiece。我还修复了其他一些位,您不需要 typedef。

编辑:刚注意到 hasPiece 是一个 int,为什么要将它初始化为 false?它应该是一个 bool 值,或初始化为 0。我已将答案更改为将其初始化为 0。

关于C++ 错误 - <unnamed-tag> 匿名 union 的成员不允许使用内置初始化程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41765355/

相关文章:

c++ - 如何从 C++ 中的 PID 获取进程名称?

python - 更改端口号导致导入错误 Django

angularjs - 在 Visual Studio 2013 中运行 Protractor 测试

c# - F5 发出噪音不运行,Ctrl+F5 运行正常,F11 的行为与 F5 完全一样?

c++ - 在模板中输入条件

c++ - 基类中的成员函数包装器

c++ - 返回 boolean 值时,为什么使用 "!!"

Qt Creator 支持 C++11 IDE?

c# - 来自多个测试类的单元测试似乎是交错的

c# - 如何向 Visual Studio 扩展添加额外的工具窗口?