C ++中的未知类型名称

问题描述

我在Life中不断收到“未知类型名称'world.h'”,并在“未知类型名称'Life'”和“未知类型名称'World'”中获取“在game.h中。

我觉得基于其他帖子的include语句可能太多,但是在这种情况下我找不到解决方案。

任何帮助/提示将不胜感激

game.h

#pragma once

#ifndef LIFE_H
#include "life.h"
#define LIFE_H
#endif

#ifndef WORLD_H
#include "world.h"
#define WORLD_H
#endif


class Game {
public:
    // Constructor/destructor
    Game(Life **life,int numLife);
    ~Game();

    void game_loop();
private:
    World * m_world;
    int m_steps;
    bool m_automate;
};

world.h

#pragma once

#ifndef LIFE_H
    #include "life.h"
    #define LIFE_H
#endif

#ifndef WORLD_H
    #include "world.h"
    #define WORLD_H
#endif

class World {
public:
    // Constructor/destructor
    World();
    ~World();

    void print() const;

    bool initLife(Life *life);
    void updateWorld();
private:

    char getNextState(char state,char row,char col,bool toggle) const;

    char **m_grid_1;
    char **m_grid_2;
    bool m_toggle;
};

life.h(无任何错误

#ifndef life_h
#define life_h

#ifndef life_h
    #include "life.h"
    #define life_h
#endif

#ifndef GAME_H
    #include "game.h"
    #define GAME_H
#endif

class Life {
public:

    int getCol() const; // const member functions cannot modify member variables.
    int getRow() const;
    int getHeight() const;
    int getWidth() const;
    char getFromfigure(int r,int c) const;

protected:
    int m_col;
    int m_row;
    int m_height;
    int m_width;
    char **m_sprite;
    World *m_world;
};
#endif

解决方法

您正在有效地仔细瞄准并在这里精确射击自己的脚。

#ifndef life_h
#define life_h

#ifndef life_h
    #include "life.h"
    #define life_h
#endif

请注意,您定义了阻止包含您自己的头文件的内容。

这非常类似于以下代码:

int loaded = 1;

if (!loaded) {
  // Why doesn't this run!?
}

如果您的目标编译器支持#pragma once,请删除所有这些,仅在顶部附近的每个头文件中添加#pragma once

否则,您需要单独的文件门,仅

// example.h
#ifndef EXAMPLE_H
#define EXAMPLE_H

...

#endif

#define的名称是从文件名得出的,并且在整个应用程序中是唯一的