我在编写代码时遇到了此类问题,我该如何解决?
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/