头文件中的 C++ 循环依赖

标签 c++ header-files circular-dependency

是否有可能避免以下头文件中的循环依赖而无需A类中的数据成员b1转换为指针/引用,并且放宽B类中的内联函数要求?

嗯:

#ifndef A_H
#define A_H
#include <B.h> // Required, as data member b1 is not a pointer/reference

class A {
    public:
        B b1; // I want to keep this as as it is.
        int m_a;
};

#endif

B.h:

#ifndef B_H
#define B_H
#include <A.h> // Required, as f() calls a member function of class A

class B {
    public:
       int f(A &a){return a.m_a;} // I want this to be an inline function.
};

#endif

...假设 main.ccp 是:

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

int main() {
    A a;
    B b;

    std::cout << "Calling b.f(a): " << b.f(a) << std::endl;

    return 0;
}

最佳答案

你可以使用这个:

啊啊

#include <B.h>
#ifndef A_H
#define A_H

class A 
{
public:
    B b1;
    int m_a;
};

#endif // A_H

B.h

#ifndef B_H
#define B_H

class A;

class B 
{
public:
    int f(A &a);
};

#include <A.h>

inline int B::f(A &a)
{
    return a.m_a;
}

#endif // B_H

主要.cpp

#include <iostream>
#include <A.h> // these could be in any order
#include <B.h>

int main() 
{
    A a;
    B b;

    std::cout << "Calling b.f(a): " << b.f(a) << std::endl;

    return 0;
}

关于头文件中的 C++ 循环依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30223453/

相关文章:

javascript - require 的同步形式在解决循环依赖时会抛出错误,除非我重命名 require

python - 检测循环导入

c++ - 如何转发声明内部类?

c++ - 该程序无法启动,因为您的计算机缺少 freeglut.dll

c - 在 mac osx 上找不到 endian.h

c - 头文件中的函数如何链接到 .c 文件?

c++ - '{' token 之前的预期类名 - 带有头文件和 cpp 文件

c++ - 如何静态构建 Qt 5

c++ - 何时在 C++ 应用程序中使用虚拟析构函数

dependency-injection - 如何使用 Autofac 2.4.5 处理循环引用?