C++ union array and vars?

前端 未结 8 1604
日久生厌
日久生厌 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:50

    I was looking for a similair thing and eventually came up with a solution.

    I was looking to have a data storage object that I could use as both an array of values and as individual values (for end-user flexibility in writing Arduino libraries).

    Here is what I came up with:

    class data{
        float _array[3];
    
        public:
        float& X = _array[0];
        float& Y = _array[1];
        float& Z = _array[2];
    
        float& operator[](int index){
            if (index >= 3) return _array[0]; //Make this action whatever you want...
            return _array[index];
        }
        float* operator&(){return _array;}
    };
    
    
    int main(){
        data Test_Vector;
        Test_Vector[0] = 1.23; Test_Vector[1] = 2.34; Test_Vector[2] = 3.45;
    
        cout<<"Member X = "<

    Thanks to Operator overloading, we can use the data object as if was an array and we can use it for pass-by-reference in function calls (just like an array)!

    If someone with More C++ experience has a better way of applying this end product, I would love to see it!

    EDIT: Changed up the code to be more cross-platform friendly

提交回复
热议问题