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

时间:2015-05-13 19:15:50

标签: c++ header-files circular-dependency

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

A.H:

#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;
}

1 个答案:

答案 0 :(得分:4)

你可以用这个:

A.H

#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

的main.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;
}