【问题标题】:C++ circular dependency between multiple classes多个类之间的C++循环依赖
【发布时间】: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 将导致几个与拼写错误相关的错误。其他标头的存在无关紧要。

标签: c++ circular-dependency


【解决方案1】:

问题:

3x Error: function random_int() is already defined in main.cpp. Files: C.cpp, A.cpp and B.cpp 不是循环依赖造成的问题,而是因为你定义了random_int() 3 次造成的。它与类没有任何关系。

解决方案:

来自this question,您的问题可能的解决方案是:

  1. 将函数声明为静态。
  • A.hpp
   static int random int()
   {
      ...
   }
  1. 将函数声明为内联函数。
  • A.hpp
   inline int random int()
   {
      ...
   }
  1. 在头文件 (.hpp) 中声明函数并在源文件 (.cpp) 中定义它。
  • A.hpp
   ...
   int random_int();
   ...
  • A.cpp
   ...
   int random_int(){
      ...
   }
   ...

其他信息:

  1. 您有多个带有分号和大括号的拼写错误。

【讨论】:

    【解决方案2】:

    改变这个

    int random_int() {
    
    class C
    

    到这里

    int random_int();
    
    class C;
    

    我认为{ 和缺少的; 只是拼写错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-30
      • 2019-02-04
      • 2014-11-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多