包括两个文件 C++ 之间的冲突
including collision between two files 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
相关文章:
- C++LinkedList问题.数据类型之间存在冲突?没有匹配的构造函数
- 如何使 std::sort 在 std::swap 和我的命名空间的模板化交换之间没有名称冲突?
- 库之间的冲突
- 如何避免 Cocos2d-x 3.15.1 中的 MenuItemImage 和 MenuItemSprite 之间的冲突
- 包括两个文件 C++ 之间的冲突
- 如何解决两个不使用命名空间的第三方库之间的类名冲突?
- 2 个 QGraphicsPixmapItems 之间的 QT 冲突检测
- 字符串和整数之间的模板冲突
- 两个提升版本之间的冲突
- C++编译错误是由于使用 std::move 时运动构造函数与其他非运动构造函数之间的冲突
- 调用 ADL 时,表达式和命名空间之间是否会发生冲突
- 复制构造函数和模板构造函数之间的冲突
- 名称名称空间和类模板之间的冲突:不同的编译器行为
- 如何解决GMP的32位和64位库之间的冲突
- OpenCV和Tesseract之间是否存在任何冲突
- 最新版本的提升和提升几何库 (GGL) 之间的冲突
- 包含:stdafx.h 和 <vector> VisualStudio 2012 C++ 之间的冲突(错误 C2953:已定义类模板)
- 类名和枚举值之间的冲突:无需命名空间即可解析
- C Socket 和 Omnet++ 之间的方法名称冲突
- 在类层次结构中,完美的转发构造函数和复制构造函数之间的冲突