为什么静态成员函数不能有 cv 限定符?
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)。
static
成员 不得virtual
功能。不得有static
和非static
成员职能,具有 相同的名称和相同的参数类型 (13.1)。静态成员函数不得声明
const
,volatile
,或const volatile
。
static
函数没有this
参数。他们不需要简历限定符。
查看詹姆斯·麦克内利斯的回答
将
const
限定符应用于非静态成员函数时, 它会影响this
指针。 对于常量限定成员函数 在类C
中,this
指针的类型为C const*
,而对于 不是常量限定的成员函数,this
指针为 键入C*
。
static
成员函数未绑定到其类的实例,因此const
和/或volatile
(即"cv-qualified")没有意义,因为在调用该函数时没有可以应用const
或volatile
的实例。
在那里写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
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 如何在C++中使用非静态成员函数作为回调函数
- (C++)为什么静态成员可以在初始化之前使用
- 类的全局对象和静态成员
- 在作为静态成员包含在另一个类中的类的构造函数中使用 cout
- 模板化类中静态成员的延迟初始化
- 使用静态成员声明类时遇到问题
- C++:是否可以使用非静态成员变量模板?
- 静态成员函数使用相同的名称时出现模板类型名称错误
- 如何在复杂继承中访问静态成员变量
- 在 nullptr 上调用无状态类的非静态成员函数是否合法?
- 如何在友元函数中使用静态成员而不添加前缀 [类名]::
- C++构造函数和静态成员
- 为什么传递非静态成员函数会导致编译错误?
- 非静态成员失败的线程调用函数
- 静态成员变量不会由 gettext 转换
- decltype:使用指针访问类的静态成员
- 处理类内的回调时,必须调用对非静态成员函数的引用
- 非静态成员函数的 decltype 格式不正确吗?
- 为什么静态成员函数不能有 cv 限定符?