【问题标题】:Forward declaration of anonymous typedef with bitfields in C++在 C++ 中使用位域前向声明匿名 typedef
【发布时间】:2017-01-31 08:43:18
【问题描述】:

我找到了 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 的正确方法是什么?

谢谢你! 兹拉坦

【问题讨论】:

  • 您需要在您的b.h 中包含文件a.h。如果这样做,则无需将文件包含在 b.cpp 中。
  • 抱歉,我想避免在 b.h 中包含 a.h。
  • 我希望typedef struct bah bah; 在实践中工作,但我不确定它是否定义明确。问题是该类没有名称供您声明...
  • 为什么要使用 typedef?在 C++ 中不需要这样做,只需编写 struct bah { ... } 并且通过编写 struct bah 前向声明应该可以正常工作;

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


【解决方案1】:

我想避免在 b.h 中包含 a.h

太糟糕了。 b.h 取决于来自 a.h 的 bah 的定义。您的需求与语言规则不一致。

如何避免这个错误

选项 1:在 b.h 中包含 a.h。我知道你不想要这个,但我想包括所有可用的选项。

选项 2:不要依赖 b.h 中的 a.h 定义。一个例子:

// b.h
class foo {
    foo();
};

可以仅使用bah 的前向声明来定义以下类:

class foo {
    foo(bah* b);
    bah* mBah;
};

但是,除非您可以转发声明结构,否则即使这样也是不可能的。所以这将我们带到......

在这种情况下转发 declarte bah 的正确方法是什么?

没有办法转发声明一个未命名的结构。除非您可以修改 a.h,否则您不能为结构指定标签名称。假设你可以改变 a.h,你会这样做:

typedef struct bah { // struct now has the tag name bah
    // ...
} bah;

由于结构的名称使 typedef 大多是多余的,您可以简化为:

 struct bah {
    // ...
 };

在这个添加之后,你可以转发声明:

struct bah;

但是前向声明不允许你声明bah类型的变量。


PS。位域对前向声明的工作方式没有影响。

【讨论】:

  • 好的,现在我知道这对于匿名 typedef 是不可能的。感谢您的努力!
【解决方案2】:

您的解决方案中有太多依赖项。 在代码的公共部分定义一次 blah。您将避免重新定义。

我建议像你一样在 a.h 中定义 blah,然后:

1) 在 b.h 中包含 a.h。在 b.cpp 中包含 b.h

2) 或在 b.cpp 中的 b.h 之前包含 a.h

【讨论】:

  • 好的,现在我知道这对于匿名 typedef 是不可能的。感谢您的努力!
猜你喜欢
  • 1970-01-01
  • 2013-06-02
  • 1970-01-01
  • 2010-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-13
相关资源
最近更新 更多