gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:14:28 40 4
gpt4 key购买 nike

是否有可能避免以下头文件中的循环依赖而无需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/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com