Pointer to class data member “::*”

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

    Pointers to classes are not real pointers; a class is a logical construct and has no physical existence in memory, however, when you construct a pointer to a member of a class it gives an offset into an object of the member's class where the member can be found; This gives an important conclusion: Since static members are not associated with any object so a pointer to a member CANNOT point to a static member(data or functions) whatsoever Consider the following:

    class x {
    public:
        int val;
        x(int i) { val = i;}
    
        int get_val() { return val; }
        int d_val(int i) {return i+i; }
    };
    
    int main() {
        int (x::* data) = &x::val;               //pointer to data member
        int (x::* func)(int) = &x::d_val;        //pointer to function member
    
        x ob1(1), ob2(2);
    
        cout <

    Source: The Complete Reference C++ - Herbert Schildt 4th Edition

提交回复
热议问题