Pointer to class data member “::*”

后端 未结 15 1645
清歌不尽
清歌不尽 2020-11-21 11:47

I came across this strange code snippet which compiles fine:

class Car
{
    public:
    int speed;
};

int main()
{
    int Car::*pSpeed = &Car::speed;
         


        
15条回答
  •  独厮守ぢ
    2020-11-21 12:01

    You can use an array of pointer to (homogeneous) member data to enable a dual, named-member (i.e. x.data) and array-subscript (i.e. x[idx]) interface.

    #include 
    #include 
    
    struct vector3 {
        float x;
        float y;
        float z;
    
        float& operator[](std::size_t idx) {
            static float vector3::*component[3] = {
                &vector3::x, &vector3::y, &vector3::z
            };
            return this->*component[idx];
        }
    };
    
    int main()
    {
        vector3 v = { 0.0f, 1.0f, 2.0f };
    
        assert(&v[0] == &v.x);
        assert(&v[1] == &v.y);
        assert(&v[2] == &v.z);
    
        for (std::size_t i = 0; i < 3; ++i) {
            v[i] += 1.0f;
        }
    
        assert(v.x == 1.0f);
        assert(v.y == 2.0f);
        assert(v.z == 3.0f);
    
        return 0;
    }
    

提交回复
热议问题