如何从结构调用静态类方法?

c00*_*0fd 3 c++ struct class visual-studio-2008

我一直在避免在 C++ 中C++03使用以下内容(我相信在 VS 2008 中使用过),但现在我很好奇是否可以这样做?让我用代码解释一下。

//Definitions.h header file
//INFO: This header file is included before CMyClass definition because
//      in contains struct definitions used in that class

struct MY_STRUCT{
    void MyMethod()
    {
        //How can I call this static method?
        int result = CMyClass::StaticMethod();
    }
};
Run Code Online (Sandbox Code Playgroud)

然后:

//myclass.h header file
#include "Definitions.h"

class CMyClass
{
public:
    static int StaticMethod();
private:
    MY_STRUCT myStruct;
};
Run Code Online (Sandbox Code Playgroud)

和:

//myclass.cpp implementation file

int CMyClass::StaticMethod()
{
    //Do work
    return 1;
}
Run Code Online (Sandbox Code Playgroud)

Gre*_*ill 5

在这种情况下,您需要将 的实现移到MY_STRUCT::MyMethod头文件之外,并将其放在其他地方。这样你就可以在Definitions.h没有CMyClass声明的情况下包含。

所以你Definitions.h会改为:

struct MY_STRUCT{
    void MyMethod();
};
Run Code Online (Sandbox Code Playgroud)

然后在其他地方:

void MY_STRUCT::MyMethod()
{
    int result = CMyClass::StaticMethod();
}
Run Code Online (Sandbox Code Playgroud)