我确实有一个如下所示的类:
I do have a class which looks like below:
//.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 中定义,并且在您的程序中再次定义它们是错误的.
__declspec(dllimport)
means that the current code is using the DLL that implements your class. The member functions and static data members are thus defined in the DLL, and defining them again in your program is an error.
如果您尝试为实现此类的 DLL 编写代码(从而定义成员函数和静态数据成员),那么您需要改为标记类 __declspec(dllexport)
.
If you are trying to write the code for the DLL that implements this class (and thus defines the member functions and static data members) then you need to mark the class __declspec(dllexport)
instead.
为此使用宏是很常见的.在构建 DLL 时,您定义一个宏 BUILDING_MYDLL
或类似的.在 MyClass
的标题中,你有:
It is common to use a macro for this. When building your DLL you define a macro BUILDING_MYDLL
or similar. In your header for MyClass
you then have:
#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 的应用程序之间共享标头.
This means that you can share the header between the DLL and the application that uses the DLL.
这篇关于dllimport静态数据成员的C++定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!