我正在尝试设置模拟程序。模拟运行了许多步骤,模拟类应该调用一堆不同类的:: step(),其中一个是_experiment类。
我无法使其工作,因为实验类需要模拟类,模拟类需要知道实验类是什么,因此它们是循环相关的。我尝试使用前向声明来解决它,但后来我无法访问前向声明类的方法。那么前方宣布的重点是什么?谁能帮我?谢谢!
的main.cpp
int main()
{
_experiment experiment;
}
experiment.cpp:
#include "experiment.h"
_experiment::experiment()
{
_simulation simulation;
simulation.experiment = this;
simulation.start();
}
void _experiment::step()
{
//Apply forces to simulation
}
experiment.h:
#include "simulation.h"
class _experiment {
public:
void step()
};
simulation.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
}
}
simulation.h:
class _experiment; //Forward declaration
class _simulation {
public:
_experiment* experiment
void run();
};
答案 0 :(得分:0)
您在simulation.cpp中没有_experiment
的定义,请在源文件中包含experiment.h文件,并且所有文件都应该有效。
此外,_experiment
类似乎在您的示例中不使用_simulation
,因此无需在experiment.h中包含simulation.h。同时将include guards添加到您的标头文件中。
答案 1 :(得分:0)
experiment.h
不需要包含simulation.h
或转发声明_simulation
,因为_experiment
的定义根本不依赖于_simulation
。
您已经在_experiment
中有前瞻性声明或simulation.h
,这很好,因为_simulation
的定义包含指向_experiment
的指针,所以不需要完整的定义。
缺少的是源文件中两个类的定义。包括两个源文件中的两个头文件,因为它们确实需要类定义,一切都应该是好的。
通常,如果您在源文件中包含所需的所有标头,并且只需要包含来自另一个标头的标头,那么您需要的不仅仅是前向声明,那么您将主要避免循环依赖性问题。
您还需要在标题中添加包含保护,以避免在需要包含其他标题的标题时出现多个定义。
前方宣布的重点是什么?
它允许您声明一个类存在,而不必声明该类所依赖的任何其他内容。您可以执行一些有用的操作,例如定义指针或对类的引用,或者使用类作为参数或返回类型声明函数,只使用前向声明。你不能做任何需要了解班级规模或成员的事情。