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

How to call static class method from a struct?

本文关键字:静态 静态类 类方法 调用 结构      更新时间:2023-10-16

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

//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();
    }
};

然后:

//myclass.h header file
#include "Definitions.h"
class CMyClass
{
public:
    static int StaticMethod();
private:
    MY_STRUCT myStruct;
};

和:

//myclass.cpp implementation file
int CMyClass::StaticMethod()
{
    //Do work
    return 1;
}

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

因此,您的Definitions.h将更改为:

struct MY_STRUCT{
    void MyMethod();
};

然后在其他地方:

void MY_STRUCT::MyMethod()
{
    int result = CMyClass::StaticMethod();
}