【发布时间】:2020-12-31 06:05:21
【问题描述】:
我有以下 3 个类:A、B 和 C。我收到 random_int() 的循环依赖错误,如何解决以下循环依赖?
3x 错误:函数 random_int() 已在 main.cpp 中定义。 文件:C.cpp、A.cpp 和 B.cpp
A.hpp
#include "B.hpp"
int random_int() {
class C
class A {
public:
void set_b(B& be) {b = be}
B* get_b() {return b;}
static A& getInstance()
{
static A instance;
return instance;
}
private:
B* b;
test();
}
A.cpp
#include "A.hpp"
#include "C.hpp"
void test() {
if (dynamic_cast<C*>(obj)) {
//do stuff
}
}
B.hpp
class C;
class B {
public:
std::vector<C*> nearby_cs*(C& obj);
}
B.cpp
#include "B.hpp"
#include "C.hpp"
std::vector<C*> B::nearby_cs*(C& obj) {
//do stuff
}
C.hpp
class A
class C {
void stuff();
}
C.cpp
#include "C.hpp"
#include "A.hpp"
void stuff() {
std::vector<C*> cs = A::getInstance().get_b()->nearby_cs(*this);
}
【问题讨论】:
-
究竟是什么让您得出结论,这里的问题是“循环依赖”,而不是试图分配对指针的引用?
-
“我出错了”。错误通常描述问题所在。我们可以看到这些错误吗?
-
您是否缺少一些大括号和分号?请提供minimal reproducible example 并且不要将错误消息留给自己
-
A.hpp中有 2 个错别字。将{替换为分号,并在class C之后添加分号。在C.hpp中的class A之后也应该有一个分号。类声明后也应该有分号。 -
这似乎是在测试之前编写太多代码的情况。仅包含 A.hpp 将导致几个与拼写错误相关的错误。其他标头的存在无关紧要。