使用静态非成员函数中的静态 const 成员
Using a static const member from static non-member function
>我在类中有一个私有的静态常量成员,在类实现中,我有静态函数尝试使用此常量,但它给了我错误。
//A.hpp
class A {
static const int X = 1; //<<problem here
// ....
}
我有
//A.cpp
static int DoSomething();
// ....
static int DoSomething {
int n = A::X; //<<problem here
//....
}
当我尝试使用 DoSomething
中的 X 并在static const int X = 1;
中‘const int A::X’ is private
时,我会within this context
.
我该如何解决这个问题?
您正在尝试从自由函数访问A
的私有成员。这是不允许的。
你应该让它public
,例如:
class A {
public:
static const int X = 1;
}
Jack 答案的另一种解决方案是使函数DoSomething()
非静态的,并将其声明为 A 类的friend
:
//A.hpp
class A {
static const int X = 1;
// ....
friend int DoSomething();
};
//A.cpp
int DoSomething() {
int n = A::X;
//....
}
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 如何在C++中使用非静态成员函数作为回调函数
- (C++)为什么静态成员可以在初始化之前使用
- 类的全局对象和静态成员
- 在作为静态成员包含在另一个类中的类的构造函数中使用 cout
- 模板化类中静态成员的延迟初始化
- 使用静态成员声明类时遇到问题
- C++:是否可以使用非静态成员变量模板?
- 静态成员函数使用相同的名称时出现模板类型名称错误
- 如何在复杂继承中访问静态成员变量
- 在 nullptr 上调用无状态类的非静态成员函数是否合法?
- 如何在友元函数中使用静态成员而不添加前缀 [类名]::
- C++构造函数和静态成员
- 为什么传递非静态成员函数会导致编译错误?
- 非静态成员失败的线程调用函数
- 静态成员变量不会由 gettext 转换
- decltype:使用指针访问类的静态成员
- 处理类内的回调时,必须调用对非静态成员函数的引用
- 非静态成员函数的 decltype 格式不正确吗?
- 如何在C++中定义静态成员结构