开发者

Pointer to a const member variable

I was wondering what the syntax was for a pointer to a constant member variable.

I know a pointer to a non-const member function and a pointer to a const member function are expressly different types, ie, the following are two distinct types:

typedef void (Foo::*Bar)(void);
typedef void (Foo::*ConstBar)(void) co开发者_运维百科nst;

I was wondering if the same could be said of pointers to non-const and const member variables, ie are the following two distinct types as well, and if so, what is the syntax of the latter:

typedef int (Foo::*var);
typedef int (Foo::*constVar) const; // Not the correct syntax.

Thanks.


The type of the pointer-to-member needs to match the type of the member:

typedef       int (Foo::*var);  // pointer to a data member of type 'int'
typedef const int (Foo::*cvar); // pointer to a data member of type 'const int'

The const-qualification of a member function is a part of its type, just like the return type is a part of its type.


Just to make it funnier:

typedef const int (Foo::*(Foo::*ConstBar)(void) const);

ConstBar is a pointer to a const-member function taking no arguments and returning a pointer to a const-member of type int.

A general tip of how to remember the syntax in your question: you just write it the way you would define the member of the class

void name(void) const; // const function
const int name; // const member

And then replace name by (Foo::*name), resulting in:

void (Foo::*name)(void) const; // pointer to const function
const int (Foo::*name); // pointer to const member
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜