首页 > 解决方案 > 包括两个文件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

标签: c++include

解决方案


这不是“碰撞”,而是循环依赖

对于您的情况,完全不包含头文件可以很容易地解决它,并且只使用类的前向声明

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

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


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


推荐阅读