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

标签 c++ c++11 visual-c++

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

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/

相关文章:

c++ - 使用 Arduino Mega 和 Simple-H HV Motor Shield 控制直流电机

c++ - 如果 lambda 在运行时被移动/破坏会发生什么?

visual-studio-2010 - 项不求值带有1个参数的函数

c++ - Win32 相当于 getgid

c++ - 性能计数器索引 windows pdh c

c++ - Cin:WAITING <ENTER>。两个继续 cin.ignore 不起作用

c++ - 引用失效保证会自动应用于指针吗?

c++ - 哈希表/双向链表中的内存泄漏

c++ - 在此代码中使用 memory_order_relaxed 是否正确?

c++ - 将延迟加载编写为模板类是否合理?