解决循环依赖关系 c++ 的想法

Ideas in solving circular dependency c++

本文关键字:c++ 关系 循环 依赖 解决      更新时间:2023-10-16

我在编写代码时遇到了这种问题,我该如何解决这个问题?

秒是 :

#pragma once
#include "first.h"
class second : public first
{
private:
int step;
public:
second(int value, int s) :first(value), step(s) {}
void increase() {
counter += step;
}
};

第一个h是:

#pragma once
class first 
{
protected:
int counter;
public:
first():counter(0){}
first(int a) :counter(a) {}
virtual void increase() {
counter++;
}
second getequivalent(int step) {
return second(counter, step);
}
};

我的问题是,我如何获得方法

second getequivalent(int step) {
return second(counter, step);
}

在"第一"班工作?

您必须在second的完整定义可用后实现该方法。

当您编写非模板类时,我建议将所有实现移动到单独的first.cpp/second.cpp文件并将它们链接在一起。

所以你的first.h看起来像

#pragma once
class second;  // Forward declaration to make compiler know that `second` is a class.
// Better option would be to #include "second.h", but you cannot
// do that because `class second` needs _full_ definition of `class first`
// because of inheritance, hence it _has_ to #include "first.h"
// without any troubles.
class first 
{
protected:
int counter;
public:
first();
first(int a);
virtual void increase();
second getequivalent(int step);  // Compiler don't need to know anything
// about second at this point.
};

first.cpp看起来像

#include "first.h"  // Make full definition of class first available.
#include "second.h"  // Make full definition of class second available.
first::first():counter(0){}
first::first(int a) :counter(a) {}
/*virtual */ void first::increase() {  // Should not specify 'virtual' in definition outside the class.
counter++;
}
second first::getequivalent(int step) {
return second(counter, step);
}