Pointer to class data member “::*”

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

    It's a "pointer to member" - the following code illustrates its use:

    #include 
    using namespace std;
    
    class Car
    {
        public:
        int speed;
    };
    
    int main()
    {
        int Car::*pSpeed = &Car::speed;
    
        Car c1;
        c1.speed = 1;       // direct access
        cout << "speed is " << c1.speed << endl;
        c1.*pSpeed = 2;     // access via pointer to member
        cout << "speed is " << c1.speed << endl;
        return 0;
    }
    

    As to why you would want to do that, well it gives you another level of indirection that can solve some tricky problems. But to be honest, I've never had to use them in my own code.

    Edit: I can't think off-hand of a convincing use for pointers to member data. Pointer to member functions can be used in pluggable architectures, but once again producing an example in a small space defeats me. The following is my best (untested) try - an Apply function that would do some pre &post processing before applying a user-selected member function to an object:

    void Apply( SomeClass * c, void (SomeClass::*func)() ) {
        // do hefty pre-call processing
        (c->*func)();  // call user specified function
        // do hefty post-call processing
    }
    

    The parentheses around c->*func are necessary because the ->* operator has lower precedence than the function call operator.

提交回复
热议问题