其他分享
首页 > 其他分享> > C头文件中的循环依赖关系

C头文件中的循环依赖关系

作者:互联网

是否可以避免在以下头文件中循环依赖,而不将类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

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

标签:c,header-files,circular-dependency
来源: https://codeday.me/bug/20190928/1825564.html