繁体   English   中英

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

[英]How to call static class method from a struct?

我一直在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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM