常量静态成员函数
Const Static member function
我到处都看到静态成员函数不能是常量。在下面的代码中,当我尝试使用静态成员函数为 const 的代码块执行它时,我实际上得到了输出。那么,这可能吗?还是仅受较新版本的C++支持?
#include<iostream>
using namespace std;
class s{
public:static const int x=2;
const static int fun(){
return x+1;
}
};
int main(){
s obj;
cout<<obj.x<<endl;
cout<<obj.fun()<<endl;
return 0;
}
output: 2
3
成员函数的const
限定符必须在函数参数列表之后编写,静态成员函数不允许这样做:
static int fun() const // error const qualifier is not allowed on static member function
{
你声明了一个返回const int
的函数,尽管它也没有多大意义。
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 如何在C++中使用非静态成员函数作为回调函数
- 在作为静态成员包含在另一个类中的类的构造函数中使用 cout
- 静态成员函数使用相同的名称时出现模板类型名称错误
- 在 nullptr 上调用无状态类的非静态成员函数是否合法?
- 如何在友元函数中使用静态成员而不添加前缀 [类名]::
- C++构造函数和静态成员
- 为什么传递非静态成员函数会导致编译错误?
- 非静态成员失败的线程调用函数
- 处理类内的回调时,必须调用对非静态成员函数的引用
- 非静态成员函数的 decltype 格式不正确吗?
- 为什么 std::sort 找不到合适的(静态成员)函数重载?
- std::异步与非静态成员函数
- C++无效使用非静态成员函数?
- 指向重载静态成员的函数指针 - 在unique_ptr中用作自定义删除器
- 未使用的C++未优化的静态成员函数/变量
- C++:如何返回指向非静态成员函数的指针?
- 有没有一种方法可以使全局函数/静态成员函数一次可呼出
- 函数静态成员变量
- 隐藏模板化的辅助函数——静态成员或未命名的命名空间