我确实有一个如下所示的类(class):
//.h file
class __declspec(dllimport) MyClass
{
public:
//stuff
private:
static int myInt;
};
// .cpp file
int MyClass::myInt = 0;
我得到以下编译错误:
error C2491: 'MyClass::myInt' : definition of dllimport static data member not allowed
我该怎么办?
最佳答案
__declspec(dllimport)
表示当前代码使用实现您的类的 DLL。成员函数和静态数据成员因此在 DLL 中定义,在您的程序中再次定义它们是错误的。
如果您尝试为实现该类的 DLL 编写代码(从而定义成员函数和静态数据成员),则需要改为标记类 __declspec(dllexport)
。
通常为此使用宏。在构建 DLL 时,您定义一个宏 BUILDING_MYDLL
或类似的。在 MyClass
的标题中,您将拥有:
#ifdef _MSC_VER
# ifdef BUILDING_MYDLL
# define MYCLASS_DECLSPEC __declspec(dllexport)
# else
# define MYCLASS_DECLSPEC __declspec(dllimport)
# endif
#endif
class MYCLASS_DECLSPEC MyClass
{
...
};
这意味着您可以在 DLL 和使用 DLL 的应用程序之间共享 header 。
关于dllimport静态数据成员的C++定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3491990/