简体   繁体   中英

Unknown type name in C++

I keep getting "Unknown type name ' Life '" in world.h and "Unknown type name ' Life '" and "Unknown type name ' World '" in game.h .

I have a feeling that there might be too many include statements based on other posts but I can't find the solution in this case.

Any help/hints will be greatly appreciated

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 (without any errors)

#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

You're effectively taking careful aim and shooting yourself precisely in the foot here:

#ifndef life_h
#define life_h

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

Notice you define the very thing that prevents including your own header file.

This is pretty similar to code like:

int loaded = 1;

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

If your target compiler(s) support #pragma once then remove all of this and just have #pragma once in each of your header files near the top.

Otherwise you need to gate the files individually, only :

// example.h
#ifndef EXAMPLE_H
#define EXAMPLE_H

...

#endif

Where the name of the #define is derived from the filename and is unique within the entire application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM