简体   繁体   中英

Pointing to Static Class Member

class A
{
static int x;
};

How to get the Address of x using pointer-to-member ?

Since it's static, this should be this syntax:

int *px = &A::x;  //x is static member

For non-static member, this is the syntax:

 int A::*py = &A::y; //y is non-static member

Example:

struct A
{
  static int x;
  int y;
};

int A::x=100;

int main() {
        int *px = &A::x;
        int A::*py = &A::y;

        A a;
        a.y = 200;

        cout << *px << endl;   //used just like normal pointers
        cout << a.*py << endl; //note how the pointer-to-member is used!
        cout << a.y << endl;   //a.*py and a.y are equivalent!
        return 0;
}

Output:

100
200
200

Demo : http://ideone.com/0xSdW

Note the the differences between pointer to static members, and pointer to non-static members, and how they're used!

You can use &A::x . But remember to mark as public the variable and there will be only one X for all instances of the class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM