Pointer to class data member “::*”

后端 未结 15 1916
清歌不尽
清歌不尽 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:20

    You can later access this member, on any instance:

    int main()
    {    
      int Car::*pSpeed = &Car::speed;    
      Car myCar;
      Car yourCar;
    
      int mySpeed = myCar.*pSpeed;
      int yourSpeed = yourCar.*pSpeed;
    
      assert(mySpeed > yourSpeed); // ;-)
    
      return 0;
    }
    

    Note that you do need an instance to call it on, so it does not work like a delegate.
    It is used rarely, I've needed it maybe once or twice in all my years.

    Normally using an interface (i.e. a pure base class in C++) is the better design choice.

提交回复
热议问题