C ++如何包含(循环依赖)? [英] c++ how to include (circular dependency)?
问题描述
我有Environment.h文件:
I have Environment.h file:
#include <windows.h>
#include "interfaces.h"
#ifndef ENVIRONMENT_H
#define ENVIRONMENT_H
class Environment {};
#endif
我有Interfaces.h文件:
and i have Interfaces.h file:
#ifndef INTERFACES_H
#define INTERFACES_H
class IMoving {
public:
virtual void Move() = 0;
};
#endif
在IMoving接口中,我想获取一个Environment类,以了解如何移动
in interface IMoving i would like to get an Environment class, to know how to move
class IMoving {
public:
virtual void Move(Environment*) = 0;
};
如果要执行此操作,则需要添加环境.h
if i want to do this i need to include environment.h
#include "Environment.h"
在这里我遇到了一个错误,因为Environment.h-包括Interfaces.h和Interfaces.h-包括Environtment.h.那么如何使其工作呢?
and here i'm getting an error, becouse Environment.h - includes Interfaces.h and Interfaces.h - includes Environtment.h. So how to make it work ?
很抱歉拼写错误
推荐答案
对于循环依赖一个可以使用转发声明
For circular dependencies one can use Forward declaration(s)
在接口定义上方的Interfaces.h中,按如下所示向前声明 Environment
:
In Interfaces.h just above interface definition, forward declare Environment
as follows:
class Environment;
然后,当您在一个类中实现IMoving时,您将在其实现文件中包含Environment.h.
Then when you implement IMoving in a class, you will include Environment.h in its implementation file.
您可以在此处了解更多信息.
You can read more about Forward declaration here.
这篇关于C ++如何包含(循环依赖)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!