为什么静态成员函数不能有 cv 限定符?

Why can't a static member function have a cv-qualifier?

本文关键字:cv 静态成员 函数 不能 为什么      更新时间:2023-10-16

这是错误:

error: static member function ‘static void myClass::myfunct()’ cannot have cv-qualifier

有人可以解释这个错误以及为什么不能使用 const 吗?

#include<iostream>
class myClass{      
   static void myfunct() const 
   { 
     //do something
   }
};
int main()
{
   //some code
   return 0;
}

值得在这里引用标准

9.4.1 静态成员函数

2) [ 注意:静态成员函数没有 this 指针 (9.3.2)。static成员 不得virtual功能。不得有static和非static成员职能,具有 相同的名称和相同的参数类型 (13.1)。

静态成员函数不得声明constvolatile,或const volatile

static函数没有this参数。他们不需要简历限定符。

查看詹姆斯·麦克内利斯的回答

const限定符应用于非静态成员函数时, 它会影响this指针。 对于常量限定成员函数 在类 C 中,this 指针的类型为 C const*,而对于 不是常量限定的成员函数,this指针为 键入 C*

static成员函数未绑定到其类的实例,因此const和/或volatile(即"cv-qualified")没有意义,因为在调用该函数时没有可以应用constvolatile的实例。

在那里写const没有意义,因为函数是static的,因此没有类实例可以灌输const上下文。因此,它被视为错误。

成员函数声明中的限定符 const 应用于指向类 this 对象的指针。由于静态函数不绑定到类的对象,因此它们没有隐式参数this。因此,限定符 const 对这些函数没有任何意义。

成员函数的 Const 限定符意味着该函数不会更改对象实例,并且可以在 const 对象上调用。静态成员函数不绑定到任何对象实例,因此它们成为 const 是没有意义的,因为您不会在任何对象上调用静态成员函数。这就是标准禁止它的原因。

class Foo
{
public:
    void memberFunc();
    static void staticMemberFunc();
}
Foo f;
f.memberFunc();          // called on an object instance
Foo::staticMemberFunc(); // not called on an object instance