【问题标题】:C++ circular includes with internal structsC++ 循环包括内部结构
【发布时间】:2012-11-14 10:15:48
【问题描述】:

我有一个关于通函的问题,这让我抓狂:

main.cpp

#include "A.hpp"
#include "B.hpp"

int main()
{
    A a();
    B b();
    return 0;
}

A.hpp

#ifndef _CLASS_A
#define _CLASS_A

#include "B.hpp"
class A
{
    public: 
        B* b;
        struct A_t
        {
            int id;
        };
};
#endif

B.hpp

#ifndef _CLASS_B
#define _CLASS_B

#include "A.hpp"

class B
{
    class A;  //Ok, with that I can use the class A
    public: 
        int a;
        A* b;  // That work!
        A::A_t *aStruct; // Opss! that throw a compilation error.

};
#endif

问题是:¿如何在 B 类中使用 A_t 结构?

我尝试添加如下前向声明:

struct  A::A_t;

但这显然确实有效。

【问题讨论】:

  • 请注意,当我们说 throw 与错误有关时,它通常意味着在运行时,即异常。如果您有编译器错误消息,请告诉我们它是什么。
  • 一一;或 A *a= 新 A();这个例子并不重要,这里只是为了说明我需要创建一个对象。

标签: c++ struct circular-dependency


【解决方案1】:

A.h 中的包含替换为前向声明。

#ifndef _CLASS_A
#define _CLASS_A
class B;
class A
{
    public: 
        B* b;
        struct A_t
        {
            int id;
        };
};
#endif

另外,请注意

A a();
B b();

不会创建类的两个实例,但它们是函数声明。你想要的

A a;
B b;

【讨论】:

  • 感谢您的快速响应,但我不能这样做:该示例当然是对真实代码的简化:我无法更改 A 类的任何内容,因此所有更改都应该是在 B.hpp 文件中制作。抱歉,如果问题的描述有点混乱。
猜你喜欢
  • 2013-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-21
  • 2015-02-12
  • 2017-05-21
  • 2012-08-11
  • 2011-07-11
相关资源
最近更新 更多