c++ - 包括两个文件c ++之间的冲突
问题描述
我遇到了碰撞问题。我的意思是在我的 Ah 中需要包含 Bh 但在 Bh 中我需要包含 Ah 所以我不知道如何修复它。
接口.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
解决方案
这不是“碰撞”,而是循环依赖。
对于您的情况,完全不包含头文件可以很容易地解决它,并且只使用类的前向声明:
文件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
您当然需要在源文件中包含头文件。
另请注意,我更改了包含警卫的符号。“实现”(编译器和标准库)在所有范围内保留带有前导下划线后跟大写字母的符号。有关详细信息,请参阅这个老问题及其答案。
推荐阅读
- wordpress - 上传 .dta 并在 wordpress 上做文件
- swift - SwiftUI 将两个子视图传递给 View
- python - 使用python中的xml树将嵌套的XML内容转换为CSV
- amazon-web-services - 在 AWS 上使用 Calico 的 Kubernetes -- 无法 ping 不同节点上的 pod
- azure-devops - 部署时无法加载 API 定义获取错误,但在 localhost 上很好
- unit-testing - 如何在堆栈中重新运行测试
- javascript - 在 JavaScript 中为每个用户同步 API 中的关键部分
- excel - 如何让数据透视表与第二个表中定义的类别层次结构一起使用
- mongodb - 将具有相似数据的对象分组并使用 mongoose 重新格式化
- ruby-on-rails - 控制器的未定义方法“get”