如何修复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_ */

最佳答案

问题在于Hero.hCreature.h相互包含:您具有循环依赖性。当Hero.h包含Creature.h并且Creature.h尝试再次包含Hero.h时,已经定义了HERO_H_,因此没有插入任何内容(如果删除了包含保护,则将得到一个无穷无尽的包含循环,不错)。

但是,似乎Creature.h实际上并没有使用Hero.h,因此您可以删除此标头。如果以后确实需要标头中的某些内容,则可以很好地摆脱前向声明。有关更多信息,请参见C ++常见问题解答条目"How can I create two classes that both know about each other?"

关于c++ - 未在此范围内声明“生物”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23854541/

10-13 08:22