c++ - C++ 中带位域的匿名 typedef 的前向声明

标签 c++ typedef forward-declaration unnamed-class

我找到了 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/

相关文章:

c++ - 插入运算符没有产生预期的输出?

c - 是否可以 typedef 不确定大小的多维数组? [C]

c++ - 模板化 typedef 中 "type"之前的预期初始化声明符

android - Godot 扩展 c++ 模块与 android 模块。有什么不同?

c++ - 通过 Internet 发送 UDP 数据报

c++ - 转发声明/什么时候最好包含标题?

c++ - 前向声明和全局命名空间声明

python - Django 模型 : mutual references between two classes and impossibility to use forward declaration in python

c++ - hash_map 不工作

c++ - 删除 C 上的非通用模板参数