How can I prevent a nameless struct\\union?

有些话、适合烂在心里 提交于 2019-12-04 07:26:52

Naming it seems best. Anonymous unions are allowed in C++, just not structs.

union
{
    struct foo
    {
        F32 _11, _12, _13, _14;
        F32 _21, _22, _23, _24;
        F32 _31, _32, _33, _34;
        F32 _41, _42, _43, _44;
    } bar;
    F32 _m[16];
};

You can use references/macros to allow access without bar.

F32& _11 = bar._11;
F32& _12 = bar._12;

Essentially the same as an anonymous struct. I don't really recommend this though. Use bar._11 if possible.


Private/public (sorta):

struct mat 
{
  struct foo 
  {
    friend class mat;
    private:
      F32 _11, _12, _13, _14;
      F32 _21, _22, _23, _24;
      F32 _31, _32, _33, _34;
      F32 _41, _42, _43, _44;
  };
  union
  {
    foo bar;
    F32 _m[16];
  };
};
codekiddy

If all you want to do is to disable the warning without changing the actual code then you can use #pragma warning directive like so:

#pragma warning(disable : 4201)

If you want to reenable it again use:

#pragma warning(default : 4201)

For addition reference, see MSDN documentation.

union
{
    struct // <- not named here
    {
        F32 _11, _12, _13, _14;
        F32 _21, _22, _23, _24;
        F32 _31, _32, _33, _34;
        F32 _41, _42, _43, _44;
    } AsStruct; // <- named here
    F32 AsArray[16];
};

I fixed it without giving the struct class a name, just the instance name.

You have this warning not about the inner struct but about union itself. Try this:

union Mat    // <-------
{
    struct
    {
        F32 _11, _12, _13, _14;
        F32 _21, _22, _23, _24;
        F32 _31, _32, _33, _34;
        F32 _41, _42, _43, _44;
    };
    F32 _m[16];
};

Mat mat;
mat._11 = 42;
F32 x = mat._22;
mat._m[ 3 ] = mat._33;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!