为什么静态成员函数不能有cv-qualifier?

时间:2013-11-06 13:01:41

标签: c++ visual-c++ static const

这是错误:

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;
}

5 个答案:

答案 0 :(得分:35)

值得引用这里的标准

9.4.1静态成员函数

  

2)[注意:静态成员函数没有this指针(9.3.2)。 -end note] static成员   功能不应是virtual。不应该有static和非static成员函数   相同的名称和相同的参数类型(13.1)。

     

不应声明静态成员函数const,   volatileconst volatile

static个函数没有this个参数。他们不需要cv资格赛。

请参阅James McNellis的this回答

  

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

答案 1 :(得分:12)

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

答案 2 :(得分:4)

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

答案 3 :(得分:1)

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

答案 4 :(得分:1)

成员函数的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
相关问题