【发布时间】:2012-01-16 18:16:09
【问题描述】:
我在AType.h 文件中有一个类,它在 AType.cpp 中实现。
# include "PrivateType.h"
class AType{
private:
int a, b, c;
PrivateType varX;
public:
...
};
我想在文件main.cpp 中使用AType 类,我需要包含AType.h,但我想避免在main.cpp 中包含PrivateType.h。
我无法使用 malloc/new 创建 varX。
main.cpp 必须在编译时知道 AType 的大小。
目前的解决方案:(不好)
1 - 创建一个程序来打印sizeof(AType)。
2 - 更改标题:
# ifdef ATYPE_CPP
# include "PrivateType.h"
#endif
class AType{
private:
# ifdef ATYPE_CPP
int a, b, c;
PrivateType varX;
# else
char data[ the size that was printed ];
# endif
public:
...
};
3 - AType.cpp 将以:
# define ATYPE_CPP
# include "AType.h"
编辑 1
有没有一种方法或工具可以自动将复杂的结构更改为 C 原始类型?
我不想打开头文件并找到结构。
如果 PrivateType 是:
struct DataType {
float a, b;
};
class PrivateType {
void* a;
int b;
short c;
DataType x;
... functions
};
AType 将更改为:
class AType {
int a, b, c;
struct x {
void* a;
int b;
short c;
struct x2{
float a, b;
};
};
};
我会分别处理复制/相等方法。
我使用 GCC 或 Clang。
编辑 2
新的解决方案?
它适用于 GCC。
1 - 获取 sizeof(AType) 和 __alignof__(AType)。
2 - 更改标题:
# ifdef ATYPE_CPP
# include "PrivateType.h"
#endif
class AType{
private:
# ifdef ATYPE_CPP
int a, b, c;
PrivateType varX;
# else
char data[ 'the sizeof(AType)' ];
# endif
public:
...
}
# ifdef ATYPE_CPP
;
# else
__attribute__ (( aligned( 'The __alignof__(AType)' ) ));
# endif
3 - 在 AType.cpp 中编写所有复制/相等方法。
会有用吗?
【问题讨论】:
-
为什么不想包含
PrivateType.h?您可以将类型粘贴到Detail命名空间中吗? -
#unclude <iostream>?disusing namespace std;? -
@JamesMcNellis 所说的是,在 C++ 中,将“私有”类型放在
namespace detail中是惯用的,这表明它们只能由实现代码访问,而不是用户代码。 -
我认为你最好使用 PIMPL 成语 - stackoverflow.com/questions/60570/…
-
@H2CO3:对齐是类型的基本属性,如果该位置针对变量的类型正确对齐,则您只能将变量安全地存储在内存位置。未修饰的
char数组不一定满足这些要求。
标签: c++ c include header-files encapsulation