我找到了 C++ 中 typedef 前向声明的答案 ( https://stackoverflow.com/a/2095798 )。但是我的情况是这样的:
// a.h
typedef struct{
unsigned char bah0 : 1;
unsigned char bah1 : 1;
unsigned char bah2 : 1;
unsigned char bah3 : 1;
unsigned char bah4 : 1;
unsigned char bah5 : 1;
unsigned char bah6 : 1;
unsigned char bah7 : 1;
} bah;
// b.h
typedef struct bah; // Error: using typedef-name 'bah' after struct
class foo {
foo(bah b);
bah mBah;
};
// b.cpp
#include "b.h"
#include "a.h"
foo::foo(bah b)
{
mBah = b;
}
而且我不允许更改 a.h
中的任何内容,我想避免在 b.h
中包含 a.h
。我怎样才能避免这个错误,或者在这种情况下转发 declarte bah 的正确方法是什么?
谢谢你! 兹拉坦
最佳答案
I want to avoid including a.h in b.h
太糟糕了。 b.h 取决于来自 a.h 的 bah
的定义。您的需求与语言规则不一致。
How can I avoid this error
选项 1:在 b.h 中包含 a.h。我知道你不想要这个,但我想包括所有可用的选项。
选项 2:不依赖于 b.h 中 a.h 的定义。一个例子:
// b.h
class foo {
foo();
};
可以仅使用 bah
的前向声明来定义以下类:
class foo {
foo(bah* b);
bah* mBah;
};
但是,除非您可以前向声明结构,否则即使这样也是不可能的。所以这将我们带到...
what is the right way to forward declarte bah in this situation?
无法转发声明未命名的结构。除非你可以修改 a.h,否则你不能给结构体一个标签名。假设你可以改变 a.h,你会这样做:
typedef struct bah { // struct now has the tag name bah
// ...
} bah;
由于结构的名称使得 typedef 大部分是多余的,您可以简化为:
struct bah {
// ...
};
添加后,可以转发声明:
struct bah;
但是前向声明不允许您声明bah
类型的变量。
附言。位字段对前向声明的工作方式没有影响。
关于c++ - C++ 中带位域的匿名 typedef 的前向声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41953089/