如何从结构中调用静态类方法
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();
}
相关文章:
- 静态 constexpr 类成员变量对多线程读取是否安全?
- 我的编译器是否忽略了我未使用的静态thread_local类成员
- 静态存储类C++计数
- 内联初始化的静态 const 类成员的初始化顺序保证
- 继承:动态派生类成员与静态派生类成员
- 避免在静态常量类上定义但不使用
- 根据模板参数可以选择静态的类成员
- 为什么不允许静态成员变量的初始化在类中,而允许静态静态成员的初始化
- 子类中具有不同值的静态基类属性
- 等效于 Java 静态对象类C++
- 是否可以按模板类型更改静态 const 类成员的值
- 如何在标题和CPP之间拆分静态/模板类
- 静态模板类成员函数的这两个调用之间有什么区别?
- 对静态重载(类)函数/方法的调用是不明确的
- 具有静态模板类成员的模板类:如何定义静态成员
- pthread没有静态的类
- 单例文件静态与类私有静态
- 使用折叠表达式初始化静态 constexpr 类数据成员不编译
- constexpr静态结构类成员的声明冲突
- 初始化在 C++ 中自定义类的构造函数中没有参数的静态 const 类成员