C++ union array and vars?

前端 未结 8 1608
日久生厌
日久生厌 2021-02-19 22:18

There\'s no way to do something like this, in C++ is there?

union {
    {
        Scalar x, y;
    }
    Scalar v[2];
};

Where x == v[0]<

8条回答
  •  旧巷少年郎
    2021-02-19 22:31

    I've used something like this before. I'm not sure its 100% OK by the standard, but it seems to be OK with any compilers I've needed to use it on.

    struct Vec2
    {
      float x;
      float y;
      float& operator[](int i) { return *(&x+i); }
    };
    

    You can add bounds checking etc to operator[] if you want ( you probably should want) and you can provide a const version of operator[] too.

提交回复
热议问题