Kem*_*mal 1 c++ circular-dependency header-files
是否有可能避免在以下头文件循环依赖而不转动数据成员B1中A类的指针/引用,而不放松在直列式功能需求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
Run Code Online (Sandbox Code Playgroud)
Bh:
#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
Run Code Online (Sandbox Code Playgroud)
...并且假设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;
}
Run Code Online (Sandbox Code Playgroud)
您可以使用此:
啊
#include <B.h>
#ifndef A_H
#define A_H
class A
{
public:
B b1;
int m_a;
};
#endif // A_H
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)