【问题标题】:How to use forward declaration with inherited files [duplicate]如何对继承的文件使用前向声明[重复]
【发布时间】:2019-08-07 03:08:35
【问题描述】:

我对前向声明有很大的问题。我有一个类,SharedContext.h,其中有一个指向另一个类StateMachine.h 的指针。 StateMachine 也有一个指向 SharedContext 的指针。如果仅此而已,这将很容易。我已经有其他类似的课程了。我只需要:

#include "StateMachine.h" 在我的SharedContext.h 文件中,并在StateMachine.h 文件中转发SharedContext,然后在StateMachine.cpp 文件中声明#include "SharedContext.h"

然而,当我需要在StateMachine 中包含更多类时,这会发生故障。我有一个State_Base.h、一个State_DIYACMenu.hState_DIYACMenu.cppState_Base.h 也有一个指向 SharedContext 的指针,需要包含它。 State_DIYACMenu.h 显然包含State_Base.h,最后我的StateMachine 包含State_DIYACMenu。所以存在循环依赖。

我想我可以通过在 State_Base.h 中使用 SharedContext 的前向声明,然后在 State_DIYACMenu.cppStateMachine.cpp 中使用 #include "SharedContext.h" 来解决这个问题。但我仍然在 StateMachine 类中收到“成员访问不完整类型 StateMachine”的错误。

github项目链接:https://github.com/djpeach/DIY-Arcade-Cabinet/tree/master/menu/menu

【问题讨论】:

  • 似乎没有最小的类示例或文件示例令人困惑。我建议的一件事是确保你也有头卫。 #pragma once 或 #ifndef SOMETHING_H #define SOMETHING_H #endif
  • 是的,我在所有头文件中都使用了一次#pragma。我三重检查了这一点。而且它的代码有点多,所以我将添加一个到 github 的链接。一瞬间
  • 我建议将代码以minimal reproducible example 形式放在问题中,而不是链接到它。链接腐烂,当这个链接消失时,这个问题就变得毫无用处了。
  • 好的,我会把它写下来。同时,有什么想法吗?

标签: c++ inheritance forward-declaration


【解决方案1】:

我建议四处走走,避免使用前向声明。

当您编写足够简单的代码时,前向声明是解决循环依赖的好方法,但是当您的代码变得越来越复杂时,由于它所暗示的各种限制,在不陷入循环依赖问题的情况下编码变得越来越困难。

要绕过它 - 使用接口类。

class My_Interface_Of_StateMachine
{
public:
    virtual ~My_Interface_Of_StateMachine() = default;
    virtual void foo() = 0;
// declarations of all functions you use
};
// put it into a header My_Interface_Of_StateMachine.h

让您的SharedContext 仅具有指向My_Interface_Of_StateMachine 的指针,并使您的StateMachine 继承自接口类My_Interface_Of_StateMachine

class StateMachine:
    public My_Interface_Of_StateMachine
{
public:
    void foo() override;
//implementation of all the functions
};

这样你就没有循环依赖了。

如果由于某种原因你发现使用虚方法太慢,那么你可以通过 cpp 文件中的动态转换将接口类转换为真实类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-10
    • 2021-07-07
    • 1970-01-01
    • 1970-01-01
    • 2022-12-04
    • 1970-01-01
    相关资源
    最近更新 更多