包括两个文件 C++ 之间的冲突



我遇到了冲突问题。我的意思是,在我的 A.h 中需要包括 B.h,但在 B.h 中我需要包括 A.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

小部件.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

由于您依赖于指针,因此您可以声明(而不是定义(类,并将头文件包含在 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

在另一个标头中执行类似的交换。

这不是"合作",而是循环依赖

对于您的情况,通过根本不包含头文件并且仅使用类的前向声明,可以轻松解决:

文件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

文件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

当然,您需要在文件中包含头文件。


另请注意,我更改了您的包含警卫的符号。带有前导下划线后跟大写字母的符号由"实现"(编译器和标准库(保留在所有范围内。有关详细信息,请参阅此旧问题及其答案。

编辑:Doctorlove更快。

在其中一个文件中使用前向声明:

#ifndef _INTERFACE_H
#define _INTERFACE_H
#include <SDL.h>
#include <vector>
#include "Widget.h"
class Widget;
class Interface
{.....
#endif

最新更新