繁体   English   中英

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

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

这是错误:

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)。 -end note] static成员函数不应是virtual 不应存在​​具有相同名称和相同参数类型的static和非static成员函数(13.1)。

静态成员函数不应声明为constvolatileconst volatile

static函数没有this参数。 他们不需要cv-qualifiers。

这个答案由詹姆斯McNellis

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

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

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

成员函数声明中的限定符const应用于指向类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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM