首页 > 解决方案 > Passing Enums Into Objects in Different Files

问题描述

So I am currently working on a text-based RPG, and I have run into an odd issue. In working on the weapon coding, I chose to go with enums for the type and rarity of the weapon. I have already programmed everything for my Weapon class; yet, when I try to create a Weapon object, I get an error having to do with my enums -- error: 'common' is not a type. The relevant code is as follows:

In Enum_Weapon.h:

#ifndef ENUM_WEAPON_H_INCLUDED
#define ENUM_WEAPON_H_INCLUDED

enum rarity{common, uncommon, rare, epic, legendary};

enum weaponType{axe, bow, crossbow, dagger, gun, mace,
                polearm, stave, sword, wand, thrown};


#endif // ENUM_WEAPON_H_INCLUDED

And in Weapon.h:

#ifndef WEAPON_H
#define WEAPON_H

#include "Item.h"
#include "Enum_Weapon.h"

class Weapon : public Item{
    public:
        Weapon();
        Weapon(rarity r, weaponType t, std::string nam, int minDam, 
               int maxDam, int stamina = 0, int strength = 0, 
               int agility = 0, int intellect = 0);

The code, of course, goes on; but this is all the code that is relevant to my error. Finally, when I try to create a Weapon object, I get the error:

#ifndef LISTOFWEAPONS_H
#define LISTOFWEAPONS_H

#include "Weapon.h"
#include "Enum_Weapon.h"

class ListOfWeapons
{
    public:
        ListOfWeapons();

    protected:

    private:
        Weapon worn_greatsword(common, sword, "Worn Greatsword", 1, 2);

};

#endif // LISTOFWEAPONS_H

The same error also happens with the sword enum. I have researched the problem, but I can't find anything similar to the issue that I am having. Any help is much appreciated!

标签: c++enumsgame-enginegame-development

解决方案


您的武器属性是函数声明,而不是变量定义。您必须在构造函数中传入默认值。

class ListOfWeapons
{
    public:
    ListOfWeapons() :
           worn_greatsword(common, sword, "Worn Greatsword", 1, 2)
      {
         //...constructor stuff
      }

protected:

private:
    //function decl
    //Weapon worn_greatsword(common, sword, "Worn Greatsword", 1, 2);
     Weapon worn_greatsword;
};

推荐阅读