pra*_*ran 78 c++ static language-lawyer const-method
今天我遇到了问题.我需要一个static会员功能,const不是必须而是更好.但是,我没有成功.任何人都可以说为什么或如何?
Jam*_*lis 123
将const限定符应用于非静态成员函数时,它会影响this指针.对于类的const限定成员函数C,this指针是类型C const*,而对于非const限定的成员函数,this指针是类型C*.
静态成员函数没有this指针(这样的函数不会在类的特定实例上调用),因此静态成员函数的const限定没有任何意义.
iam*_*ind 21
我同意你的问题,但遗憾的是C++就是这样设计的.例如:
class A {
int i; //<--- accessed with 'this'
static int s; //<---- accessed without 'this'
public:
static void foo () const // <-- imaginary const
{}
};
Run Code Online (Sandbox Code Playgroud)
截至今天,const在上下文中考虑this.在某种程度上,它是狭窄的.通过const在this指针之外应用它可以使它更广泛.
即,"建议" const,也可能适用于static功能,将限制static成员的任何修改.
在示例代码中,如果foo()可以const,那么在该函数中,A::s不能修改.如果将此规则添加到标准中,我看不到任何语言副作用.相反,为什么不存在这样的规则是有趣的!