C++ - 为什么不能使用“const"限定符创建静态成员函数

2022-01-05 00:00:00 static language-lawyer c++ const-method

今天我遇到了一个问题.我需要一个 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?

推荐答案

当您将 const 限定符应用于非静态成员函数时,它会影响 this 指针.对于 C 类的 const 限定成员函数,this 指针的类型是 C const*,而对于不是const 限定,this 指针的类型为 C*.

When you apply the const qualifier to a nonstatic member function, it affects the this pointer. For a const-qualified member function of class C, the this pointer is of type C const*, whereas for a member function that is not const-qualified, the this pointer is of type C*.

静态成员函数没有 this 指针(此类函数不会在类的特定实例上调用),因此静态成员函数的 const 限定没有任何意义.

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.

相关文章