chr*_*451 5 c++ dependencies header include
在我的C++头文件中,我尝试使用前向声明(类MyClass;)而不是#including类头,正如许多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 );
};
Run Code Online (Sandbox Code Playgroud)
到目前为止,我能想到的最好的解决方案是用成员常量替换枚举:
//// 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;
Run Code Online (Sandbox Code Playgroud)
但在这种情况下,解决方案似乎比问题更糟糕.
我目前正在通过大规模C++软件设计(Lakos)和有效的遗留代码(Feathers)工作来寻找依赖性破坏技术,但我还没有找到一个好的解决方案.
Dom*_*ger 12
这很难做得很好.将enums 移动到一个公共头文件可能是一个合理的解决方案吗?
编辑:我知道要求避免包含头文件的问题,但是没有办法(AFAIK)这样做.将枚举移动到单独的头文件至少可以最小化您需要包含的头文件中的内容量.它肯定比问题中提出的疯狂更好!
小智 6
你不能转发声明枚举值 - 而你的解决方法是完成疯狂的一步.
您是否遇到#including标头导致的任何主要编译速度下降?如果没有,只需#include他们.使用前向声明不是 "最佳实践",它是一种黑客行为.
| 归档时间: |
|
| 查看次数: |
2616 次 |
| 最近记录: |