22

假设我有一个 .hpp 文件,其中包含一个带有公共静态方法和私有静态成员/变量的简单类。这是一个示例类:

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)访问私有静态成员(TheVar)?

4

1 回答 1

25

对你的问题的回答是肯定的!您只是错过了定义静态成员TheVar

int MyClass::TheVar = 0;

在一个 cpp 文件中。

就是尊重一个定义规则

例子 :

// 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;
于 2013-08-25T21:13:34.960 回答