简体   繁体   English

无法解决循环依赖

[英]Unable to resolve circular dependency

Given following classes: 给定以下课程:

// myClass.hpp
class Child1;
class Child2;

class MyClass {
  public:
    virtual void doSomething (const MyClass&) const = 0;
    virtual void doSomething (const Child1&) const = 0;
    virtual void doSomething (const Child2&) const = 0;
};

// child1.hpp
#include "myClass.hpp"

class Child1 : public MyClass {
  public:
    virtual void doSomething (const MyClass&) const override;
    virtual void doSomething (const Child1&) const override;
    virtual void doSomething (const Child2&) const override;
};


// child2.hpp
#include "myClass.hpp"

class Child2 : public MyClass {
  public:
    virtual void doSomething (const MyClass&) const override;
    virtual void doSomething (const Child1&) const override;
    virtual void doSomething (const Child2&) const override;
};

The compiler gives me the errors: 编译器给我错误:

undefined reference to 'Child1::doSomething(MyClass const&)'

The same error is printed for the other doSomething(..) functions. 其他doSomething(..)函数也会输出相同的错误。

I'm sure there is some mistake in including files (I use include guards for every header-file!!). 我确定在包含文件时会出错(我对每个头文件都使用了包含保护措施!)。 My questions are: Where do I have to include the corresponding files and where do I need forward declaration? 我的问题是:我必须在哪里包括相应的文件,哪里需要前向声明?

"Undefined reference" looks like a linker problem. “未定义的引用”看起来像一个链接器问题。 Ensure that you have a child1.cpp including child1.hpp and that you compile and with it; 确保您拥有一个child1.cpp(包括child1.hpp)并进行编译和使用; and that child1.cpp define the override function in the correct way. 并且child1.cpp以正确的方式定义了覆盖函数。

The error tells you that there is no reference to the whole Method. 该错误告诉您没有对整个方法的引用。

In other words you need to define the Method in a *.cpp File or directly in the header. 换句话说,您需要在* .cpp文件中或直接在标题中定义方法。 See for example this overview or this similar question . 例如,请参阅此概述类似问题 The answers tell you that is actual not a Compiler error but a Linker error. 答案告诉您这实际上不是编译器错误,而是链接器错误。

Edit: As Hans Olsson Answer suggests, it could also be that you need to include your cpp files . 编辑:正如汉斯·奥尔森答案所暗示的,也可能是您需要包括cpp文件

If you do not exactly know how the implementation will look like but want to know if you header-concept works you can implement them empty 如果您不完全了解实现的外观,但是想了解标头概念是否有效,可以将其实现为空

virtual void doSomething (const MyClass&) const override {}

Or compiler your code with gcc with the flag "-c" which tells gcc enter to just do the compiling not the linking . 或者使用带有标志“ -c”的gcc编译您的代码,该代码告诉gcc enter仅进行编译而不是链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM