c++ - 消除循环依赖

标签 c++ c++11

我在使用循环依赖项进行编译时遇到问题。我做了一些研究,人们建议使用前向声明。我仍然对此有疑问,因为具有前向声明的类正在使用转发类中的方法。这导致编译器给我错误“A 类具有不完整的字段 b”。如何解决 A 需要 B 而 B 需要 A 的循环依赖?

嗯:

#ifndef A_H_
#define A_H_

#include <iostream>
//#include "B.h"

class A
{
    class B;
    private:
        B b;
    public:
        A();
        ~A();
        void method();
};
#endif

A.cpp:

#include <iostream>
#include "A.h"

A::A()
{
}

A::~A()
{
}

void A::method()
{
    b.method();
}

B.h:

#ifndef B_H_
#define B_H_

#include <iostream>
//#include "A.h"

class B
{
    class A;
    private:
        A a;
    public:
        B();
        ~B();
        void method();
};
#endif

B.cpp:

#include <iostream>
#include "B.h"

B::B()
{
}

B::~B()
{
}

void B::method()
{
    a.method();
}

最佳答案

您的类(class)无法正常工作。每个 A 都包含一个 BB 又包含一个 A,而 A 又包含一个 B,如此循环往复。

关于c++ - 消除循环依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20202231/

相关文章:

c++ - Windows 事件的等效 boost

C++多维动态数组

c++ - 在基于范围的表达式和声明中具有相同名称的标识符

c++ - 如何从我的 jamfile 中将 cxxflags 传递给 Boost 库?

c++ - 从类型 T 的数组初始化类型 T* 的 STL vector

c++ - 我如何专门化这个模板成员函数?

c++ - C++ 中的指针函数参数复制和性能

c++ - 如何解释函数模板解析?

c++ - 当另一个线程正在运行时,线程连接会导致段错误

c++ - Lambda 捕获导致不兼容的操作数类型错误?