简体   繁体   English

在向前声明类时,我是否也应该使用属性定义?

[英]When forward declaring classes should I use attribute defines there too?

When I'm forward declaring classes and I have a define like: 当我向前声明类时,我有一个如下的定义:

#define API __declspec(dllexport)

Should I declare the function with it, or without it? 我应该用它声明函数,还是没有它? I know that I need to when I'm fully declaring the class (like, with a body and stuff), but I want to know if I should use it on forward declarations aswell. 我知道我需要在完全宣布课程时(比如,有一个身体和东西),但我想知道我是否应该在前向声明中使用它。

In general my answer will be 'No'. 一般来说,我的回答是“不”。

__declspec(dllexport) and __declspec(dllimport) attributes are needed only to know the fact "we need to export this" and "we need to import this". __declspec(dllexport)__declspec(dllimport)属性只需要知道“我们需要导出这个”和“我们需要导入它”这一事实。 And in places where only forward declaration is sufficient this fact doesn't matter because it means that in this place it's enough to know just that such class exists. 在只有前向声明就足够的地方,这个事实并不重要,因为这意味着在这个地方足以知道这样的类存在。

One of the most common use cases would be like this: 最常见的用例之一是这样的:

// --- Library ---
// Library.h
class LIBRARY_API LibraryClass
{
     void SomeMethod();
}

// Library.cpp
#include "Library.h" // we include the declaration together with __declspec(dllimport)
void LibraryClass::SomeMethod() { /*do something*/ }


// --- Some module which uses Library ---
// Some class .h file
class LibraryClass; // forward declaration
class SomeClass
{
    std::unique_ptr<LibraryClass> mp_lib_class; 
    // forward decl of LibraryClass is enough 
    // - compiler does not need to know anything about this class

    // ...   
}

// Some class .cpp file
#include <Library/Library.h> 
// here we include LibraryClass declaration with __declspec(dllimport)

//...
SomeClass::SomeClass()
    : mp_lib_class(std::make_unique<LibraryClass>())
        // here we need to actually call LibraryClass code
        // - and we know that it's imported because of #include
{}

And if you are forward declaring LibraryClass inside of a Library where it's actually defined - putting __declspec(dllexport) will not change anything because class is exported no matter of these forward declarations. 如果你正在向实际定义的库中声明LibraryClass ,那么放__declspec(dllexport)将不会改变任何东西,因为无论这些前向声明如何都会导出类。

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

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