“生物”未在此范围内声明

时间:2014-05-25 10:54:25

标签: c++

如何修复Hero.h中的错误?

 GCC C++ compiler flags  : -c -fmessage-length=0 -std=gnu++11 ; 

我将g ++更新为4.8.1

// Creature.h
#pragma once

#ifndef CREATURE_H_
#define CREATURE_H_

#include <string>
#include "Hero.h"
#include "Characteristics.h"
#include <map>

class Creature
{
private:

    CreatureCharacteristics Characters;

    Creature(const std::string i_name, int i_count = 0); 
    Creature(const Creature& Donor);

public:
    typedef std::map < std::string, Creature* > Prototypes;
    static Prototypes Clones_Bank;
    ~Creature();

    const CreatureCharacteristics& Get_characteristics(){
        return this->Characters;
    }

    static Creature*& Clone(std::string i_name, int i_count = 0);
};
#endif /* CREATURE_H_ */


// Hero.h
#pragma once

#ifndef HERO_H_
#define HERO_H_

#include "Creature.h"
#include "Characteristics.h"
#include <string>
#include <vector>

typedef std::vector<Creature*> Army; // ERROR HERE (‘Creature’ was not declared in this 
     scope)


class Hero {
private:
    Army                army;
    HeroCharacteristics base_characteristics;

public:
    Hero(std::string name = '\0', int attack = 0, int defense = 0):
        hero_name(name)
    {
        base_characteristics.attack = attack;
        base_characteristics.defence = defense;
    };
    const Army& Get_army() const
    {
        return army;
    };
    const std::string& Get_name() const
    {
        return hero_name;
    };
    const HeroCharacteristics& Get_characteristics() const
    {
        return base_characteristics;
    };
    void Add_creature(Creature* creature, int creature_count);
};
#endif /* HERO_H_ */

1 个答案:

答案 0 :(得分:4)

问题是Hero.hCreature.h互相包含:你有一个循环依赖。当Hero.h包含Creature.hCreature.h尝试再次包含Hero.h时,HERO_H_已经定义,因此不会插入任何内容(如果您删除了包含警戒,你会得到一个无休止的包含周期,这也是不好的。)

但是,似乎Creature.h实际上并未使用Hero.h,因此您只需删除此标头即可。如果您以后确实需要标题中的某些内容,那么您很可能会使用前向声明。有关详细信息,请参阅C ++ FAQ条目"How can I create two classes that both know about each other?"