在C++中,当我需要使用枚举时,如何避免#include头文件?

2024-01-08

在我的 C++ 头文件中,我尝试使用前向声明 (class MyClass;) 而不是 #include 类头,正如许多 C++ 编码标准中所建议的那样(Google C++ 样式指南就是其中之一)。

不幸的是,当我引入枚举时,我无法再进行前向声明了。像这样:

//// myclass1.hpp ////

class MyClass1
{
    enum MyEnum1
    {
        Enum_A, Enum_B, Enum_C
    };
};

//// myclass2.hpp ////

// I want to avoid this
#include "myclass1.hpp"

// I'd prefer to do this (forward declaration)
class MyClass1;

class MyClass2
{
    // This is o.k.: I only need to forward declare MyClass1
    MyClass1* ptr;

    // This forces me to #include, but I don't want to!
    void func( MyClass1::MyEnum1 e );
};

到目前为止我能想到的最好的解决方案是将枚举替换为成员常量:

//// myclass1.hpp  ////

MyClass1
{
    static const int Enum_A;
    static const int Enum_B;
    static const int Enum_C;
};

//// myclass1.cpp ////

const int Enum_A = 1;
const int Enum_B = 2;
const int Enum_C = 3;

但在这种情况下,解决方案似乎比问题更糟糕。

我目前正在浏览大规模C++软件设计(拉科斯)和有效地处理遗留代码(羽毛)用于依赖破坏技术,但我还没有找到一个好的解决方案。


这很难做得很好。也许在移动enum通用头文件是一个合理的解决方案吗?

编辑:我知道问题要求避免包含头文件,但没有办法(AFAIK)做到这一点。将枚举移动到单独的头文件至少可以最大限度地减少您需要包含的头文件中的内容。这肯定比问题中建议的疯狂要好!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在C++中,当我需要使用枚举时,如何避免#include头文件? 的相关文章

随机推荐