dllimport静态数据成员的C ++定义 [英] C++ definition of dllimport static data member

查看:607
本文介绍了dllimport静态数据成员的C ++定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类如下所示:

  //。h file 
class __declspec(dllimport )MyClass
{
public:
// stuff
private:

static int myInt;
};

// .cpp文件
int MyClass :: myInt = 0;

我得到以下编译错误:

 错误C2491:'MyClass :: myInt':dllimport静态数据成员的定义不允许

我应该怎么办?

解决方案

__ declspec(dllimport)表示当前代码使用实现您的类的DLL。成员函数和静态数据成员因此在DLL中定义,并在您的程序中再次定义它们是一个错误。



如果您试图写DLL实现这个类(从而定义成员函数和静态数据成员),那么你需要标记类 __ declspec(dllexport)



通常使用宏。在构建DLL时,您可以定义一个 BUILDING_MYDLL 或类似的宏。在 MyClass 的标题中,您将有:

  #ifdef BUILDING_MYDLL 
#define MYCLASS_DECLSPEC __declspec(dllexport)
#else
#define MYCLASS_DECLSPEC __declspec(dllimport)
#endif

class MYCLASS_DECLSPEC MyClass
{
...
};

这意味着您可以在DLL和使用DLL的应用程序之间共享标头。 p>

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;

I get the following compile error:

error C2491: 'MyClass::myInt' : definition of dllimport static data member not allowed

what should I do?

解决方案

__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.

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.

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 BUILDING_MYDLL
#define MYCLASS_DECLSPEC __declspec(dllexport)
#else
#define MYCLASS_DECLSPEC __declspec(dllimport)
#endif

class MYCLASS_DECLSPEC MyClass
{
    ...
};

This means that you can share the header between the DLL and the application that uses the DLL.

这篇关于dllimport静态数据成员的C ++定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆