gpt4 book ai didi

c++ - 解决循环依赖的想法C++

转载 作者:行者123 更新时间:2023-12-02 10:16:28 25 4
gpt4 key购买 nike

我在编写代码时遇到了此类问题,我该如何解决?

second.h是:

#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;
}

};

并且first.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);
}

关于c++ - 解决循环依赖的想法C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61770555/

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