指向 const 成员变量的指针
我想知道指向常量成员变量的指针的语法是什么。
我知道指向非常量成员函数的指针和指向常量成员函数的指针显然是不同的类型,即以下是两种不同的类型:
typedef void (Foo::*Bar)(void);
typedef void (Foo::*ConstBar)(void) const;
我想知道指向非常量和常量的指针是否也可以这样说成员变量,即也有以下两种不同的类型,如果是,后者的语法是什么:
typedef int (Foo::*var);
typedef int (Foo::*constVar) const; // Not the correct syntax.
谢谢。
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) const;
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
指向成员的指针的类型需要与成员的类型匹配:
成员函数的 const 限定是其类型的一部分,就像返回类型是其类型的一部分一样。
The type of the pointer-to-member needs to match the type of the member:
The const-qualification of a member function is a part of its type, just like the return type is a part of its type.
只是为了让它更有趣:
ConstBar 是一个指向 const 成员函数的指针,不带参数并返回一个指向 int 类型的 const 成员的指针。
关于如何记住问题中的语法的一般提示:您只需按照定义类成员的方式编写它
,然后将
name
替换为(Foo::*name)< /代码>,结果是:
Just to make it funnier:
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
And then replace
name
by(Foo::*name)
, resulting in: