简体   繁体   中英

Pointers to static members of class

From this reference:

(8.3.3/3) A pointer to member shall not point to a static member of a class (9.4), a member with reference type, or " cv void."

Why a pointer cannot point to a static member of a class?

struct S {
     static int f() { /*...*/ };

};

int main()
{
     int (S::*s)() = &S::f; // why?
}

Why a pointer cannot point to a static member of a class?

Because for the purpose of membership it isn't a member, merely for the purpose of scope. Apart from scope, static members are just like free functions, unattached to an instance of a class. You can use non-member function pointers:

int (*s)() = &S::f;

Whenever you do T::* , you're saying "this thing requires an instance of T to use." That statement does not hold for static functions, which are callable without any instances of the class.

You'd have to use a regular function pointer, like so:

int (*s)()=&S::f;

Like GMan said, static methods don't work on instances, so they don't receive the hidden this pointer. This effectively makes them have a different signature from instance methods with the same arguments.

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