假设我有一个 .hpp 文件,其中包含一个带有公共(public)静态方法和私有(private)静态成员/变量的简单类。 这是一个示例类:
class MyClass
{
public:
static int DoSomethingWithTheVar()
{
TheVar = 10;
return TheVar;
}
private:
static int TheVar;
}
当我打电话时:
int Result = MyClass::DoSomethingWithTheVar();
我希望“结果”等于 10;
相反,我得到(在第 10 行):
undefined reference to `MyClass::TheVar'
第 10 行是“TheVar = 10;”从方法。
我的问题是是否可以从静态方法 (DoSomethingWithTheVar) 访问私有(private)静态成员 (TheVar)?
最佳答案
对您的问题的回答是肯定的!您只是错过了定义静态成员 TheVar
:
int MyClass::TheVar = 0;
在 cpp 文件中。
是尊重One definition rule .
例子:
// Myclass.h
class MyClass
{
public:
static int DoSomethingWithTheVar()
{
TheVar = 10;
return TheVar;
}
private:
static int TheVar;
};
// Myclass.cpp
#include "Myclass.h"
int MyClass::TheVar = 0;
关于C++从公共(public)静态方法访问私有(private)静态成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18433752/