c++ - 调用循环依赖类的成员方法

标签 c++ class forward-declaration cyclic-dependency

我正在尝试设置模拟程序。模拟运行了多个步骤,模拟类应该调用一堆不同类的::step() ,其中一个是 _experiment 类。

我无法让它工作,因为实验类需要模拟类,而模拟类需要知道实验类是什么,所以它们是循环依赖的。我已经尝试通过使用前向声明来解决它,但是我无法访问前向声明类的方法。那么前向声明的意义何在?谁能帮我?谢谢!

主要.cpp

int main()
{
    _experiment experiment;
}

实验.cpp:

#include "experiment.h"

_experiment::experiment()
{
    _simulation simulation;
    simulation.experiment = this;
    simulation.start();
}

void _experiment::step()
{
    //Apply forces to simulation
}

实验.h:

#include "simulation.h"

class _experiment {
public:
    void step()
};

模拟.cpp:

#include "simulation.h"

void _simulation::run()
{
    //Run simulation for 1000 steps
    for(int i = 0; i < 1000; i++)
    {
        experiment->step() //Calculate forces. Doesnt work (cant use member functions of forward declared classes. How to work around this?

        //Calculate motion
    }
}

模拟.h:

class _experiment; //Forward declaration

class _simulation {
public:
     _experiment* experiment
     void run();
};

最佳答案

experiment.h不需要包含simulation.h,或者前向声明_simulation,因为_experiment<的定义 根本不依赖于 _simulation

您已经在 simulation.h 中有一个前向声明或 _experiment,这很好,因为 _simulation 的定义包含指向_experiment,所以不需要完整的定义。

缺少的是源文件中两个类的定义。包括来自两个源文件的两个 header ,因为它们确实需要类定义,一切都应该是好的。

一般来说,如果您在源文件中包含您需要的所有 header ,并且仅在您需要的不仅仅是前向声明时包含来自另一个 header 的 header ,那么您将主要避免循环依赖问题。

您还需要向 header 添加包含防护,以避免在确实需要包含来自其他 header 的 header 的情况下出现多个定义。

What is the point of forward declaring then?

它允许您声明一个类存在,而不必声明该类所依赖的任何其他内容。您可以做一些有用的事情,例如定义指针或对类的引用,或者使用类作为参数或返回类型声明函数,仅使用前向声明。您无法做任何需要了解类(class)规模或成员的事情。

关于c++ - 调用循环依赖类的成员方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8491537/

相关文章:

c++ - friend 类需要包含或转发声明 C++?

c++ - TCHAR[] 转换为字符串

c++ - 是否可以将整数的每个数字存储到 char 数组中?

c++ - 如何正确初始化不可默认构造的类成员?

C++ 重载括号 [] 运算符 get & set 具有不同的返回类型

属性和方法具有相同名称的 JavaScript 类

c++ - 在 C++11 中使用的前向声明

c++ - Boost 容器无法使用未定义(但已声明)的类进行编译

c++ - C++ 和数组中的通用交换函数

c++ - 获取回调函数的返回类型