只包含在cpp文件中

时间:2016-08-25 14:28:53

标签: c++

我想在.cpp文件中包含,因为我在一个项目中工作,有很多类必须互相交流,我觉得它有点好,因为你没有担心你已经包括或不包括的内容,我只是不知道该怎么做; 这是一个例子:

#include "UnitConverter.hpp"
#include <string>
//extern namespace std;
//extern class  std::string;
//extern class UnitConverter;
//extern enum UnitConverter::UnitTypes;
//extern enum UnitConverter::UnitSystem;
//extern enum UnitConverter::ScalingType;

class AnalogOutput{

    public:
    std::string name;
    UnitConverter::UnitTypes unit_type;
    UnitConverter::UnitSystem unit_system;
    UnitConverter::ScalingType scaling_type;
}

我如何声明命名空间,类和枚举类型,以便在hpp文件中但不在cpp文件中编译?

3 个答案:

答案 0 :(得分:6)

您可以使用包含在其中包含您需要的所有内容的标题来实现此目的。

使用catch-all标头会导致编译时间停止。厉害。唐&#39;吨。做。它

答案 1 :(得分:2)

听起来你问的是使用forward declarations。为此,语法只是class MyClass;(您不需要那些extern前缀。)

要转发声明一个驻留在命名空间中的类,请在命名空间中包装前向声明:

namespace MyNamespace {
    class MyClass;
}

但是,这里至少有两个与您的代码段相关的重要注意事项:

  1. 您只能对转发使用指针或引用 声明的类型。因此,在您的示例中,如果您希望在std::string课程中拥有std::string成员,则无法转发声明AnalogOutput - 您必须将该成员更改为改为使用指针或引用。
  2. You can't forward declare nested types。因此,您无法转发声明enums,因为它们都嵌套在UnitConverter中。

答案 2 :(得分:2)

std::string会让你感到困难,因为它是模板的typedef ...最好不要担心那个 - 你不太可能得到循环包含系统标题..

对于您的项目的类,您必须完全按照它们在相应标题中声明的方式声明它们:

// Example.h
namespace Dummy
{
    class Example { /* ... */ };
}

然后避免包括:

// Test.h
namespace Dummy
{
    class Example; // just the bare name!
}

但要注意这样,你得到的类型不完整,你不能直接使用它们。您可以使用指针或对它们的引用,但以下组合不会起作用:

// Test.h
/* ... */
class Test
{
    Dummy::Example ex;    // type is incomplete!
    Dummy::Example& ex_r; // reference is OK
    Dummy::Example* ex_p; // pointer, too

    inline void foo()
    {
        // type incomplete; you cannot do this here:
        ex_p->bar();
        // needs to be done in cpp file where Example.h is included instead
    }
};