[英]including collision between two files c++
I 've got a collision issue. 我遇到了碰撞问题。 I mean that in my Ah in need to include Bh but in Bh I need to include Ah so I can't figure out how to fixe it. 我的意思是,在我的Ah中需要包含Bh,但在Bh中我需要包含Ah,所以我不知道如何解决它。
Interface.h 接口.h
#ifndef _INTERFACE_H
#define _INTERFACE_H
#include <SDL.h>
#include <vector>
#include "Widget.h"
class Interface
{
public:
Interface(SDL_Rect &r);
~Interface();
private:
SDL_Rect m_rect;
std::vector<Widget*> m_widgets;
};
#endif
Widget.h Widget.h
#ifndef _WIDGET_H
#define _WIDGET_H
#include <SDL.h>
#include "Interface.h"
class Widget
{
public:
Widget(Interface *main, SDL_Rect &r);
~Widget();
private:
SDL_Rect m_rect;
Interface* m_master;
};
#endif
Since you rely on pointers, you can declare (rather than define) the classes, and include the header files in the cpp files: 由于依赖指针,因此可以声明(而不是定义)类,并将头文件包括在cpp文件中:
#ifndef _INTERFACE_H
#define _INTERFACE_H
#include <SDL.h>
#include <vector>
class Widget; //See the swap from include to declaration?
class Interface
{
public:
Interface(SDL_Rect &r);
~Interface();
private:
SDL_Rect m_rect;
std::vector<Widget*> m_widgets;
};
#endif
Do a similar swap in the other header. 在另一个标头中进行类似的交换。
That's not a "collosion" but a circular dependency . 那不是“共谋”,而是循环依赖 。
For your case it's solved very easily by not including the header files at all, and only use forward declarations of the classes: 对于您的情况,通过完全不包括头文件,而仅使用类的前向声明 ,可以很容易地解决该问题:
File Interface.h
: 文件Interface.h
:
#ifndef INTERFACE_H
#define INTERFACE_H
#include <SDL.h>
#include <vector>
// No inclusion of Widget.h
// Forward declare the class instead
class Widget;
class Interface
{
public:
Interface(SDL_Rect &r);
~Interface();
private:
SDL_Rect m_rect;
std::vector<Widget*> m_widgets;
};
#endif
File Widget.h
: 文件Widget.h
:
#ifndef WIDGET_H
#define WIDGET_H
#include <SDL.h>
// Don't include Interface.h
// Forward declare it instead
class Interface;
class Widget
{
public:
Widget(Interface *main, SDL_Rect &r);
~Widget();
private:
SDL_Rect m_rect;
Interface* m_master;
};
#endif
You of course needs to include the header files in your source files. 当然,您需要在源文件中包含头文件。
Also note that I changed the symbols for your include guards. 另请注意,我已更改了包括防护的符号。 Symbols with a leading underscore followed by an upper-case letter are reserved in all scopes by the "implementation" (the compiler and standard library). 在所有范围内,由“实现”(编译器和标准库)保留带下划线的字母符号和大写字母。 See this old question and its answers for details. 有关详细信息,请参见此旧问题及其答案 。
EDIT: Doctorlove was faster. 编辑:Doctorlove更快。
use forward declaration in one of the files: 在其中一个文件中使用前向声明:
#ifndef _INTERFACE_H
#define _INTERFACE_H
#include <SDL.h>
#include <vector>
#include "Widget.h"
class Widget;
class Interface
{.....
#endif
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.