为什么静态成员函数不能有 const 限定符?
今天我遇到了一个问题。我需要一个 static
成员函数,const
不是必须的,而是更好的。但是,我的努力并没有成功。有人能说出为什么或如何吗?
Today I got a problem. I am in the need of a static
member function, const
is not a must but a better. But, I didn't succeed in my efforts. Can anybody say why or how?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
当您将 const 限定符应用于非静态成员函数时,它会影响 this 指针。对于
C
类的 const 限定成员函数,this
指针的类型为C const*
,而对于非 const 限定的成员函数const 限定的,this
指针的类型为C*
。静态成员函数没有
this
指针(这样的函数不会在类的特定实例上调用),因此静态成员函数的 const 限定没有任何意义。When you apply the
const
qualifier to a nonstatic member function, it affects thethis
pointer. For a const-qualified member function of classC
, thethis
pointer is of typeC const*
, whereas for a member function that is not const-qualified, thethis
pointer is of typeC*
.A static member function does not have a
this
pointer (such a function is not called on a particular instance of a class), so const qualification of a static member function doesn't make any sense.我同意你的问题,但不幸的是 C++ 就是这样设计的。例如:
从今天开始,
const
被认为是在this
的上下文中。从某种程度上来说,它是狭窄的。通过在this
指针之外应用此const
可以使其变得更宽。即“建议的”const(也可能适用于静态函数)将限制静态成员的任何修改。
在示例代码中,如果可以将
foo()
设为const
,则在该函数中,A::s
不能被修改。如果将此规则添加到标准中,我看不到任何语言副作用。相反,有趣的是为什么这样的规则不存在!I agree with your question, but unfortunately the C++ is designed that way. For example:
As of today, the
const
is considered in context ofthis
. In a way, it's narrow. It can be made broader by applying thisconst
beyondthis
pointer.i.e. the "proposed"
const
, which may also apply tostatic
functions, will restrict thestatic
members from any modification.In the example code, if
foo()
can be madeconst
, then in that function,A::s
cannot be modified. I can't see any language side effects, if this rule is added to standard. On the contrary, it's amusing that why such rule doesn't exist!不幸的是,C++ 不按照设计接受它,但从逻辑上讲,它验证良好的用例很少。
类级别有效(静态)的函数可能不会更改任何静态数据,可能只是查询数据应该是常量。
也许应该是这样
It is unfortunate that C++ doesn't accept it as per design but logically there are few use cases in which it validates well.
A function which is class level valid(static) might not change any static data, may be it will just query data should be const.
May be it should be like
不用深究细节,这是因为函数可能会或可能不会修改对象,所以 const 对于编译器来说是不明确的。
回想一下,
const
保持对象不变,但这里可能有也可能没有一个对象来保持不变。Without getting into the details, it's because there may or may not be an object modified by the function, so const is ambiguous to the compiler.
Recall that
const
keeps objects constant, but there may or may not be an object here to keep constant.“const 成员函数”不是
允许修改调用它的对象,但静态成员
不会在任何对象上调用函数。
它由范围解析运算符直接使用。
因此拥有 const static 成员函数是没有意义的,因此它是非法的。
A 'const member function' is not
allowed to modify the object it is called on, but static member
functions are not called on any object.
It is used directly by scope resolution operator.
Thus having a const static member function makes no sense, hence it is illegal.