将枚举传递到不同文件中的对象中

Passing Enums Into Objects in Different Files

本文关键字:文件 对象 枚举      更新时间:2023-10-16

所以我目前正在开发一个基于文本的RPG,我遇到了一个奇怪的问题。在进行武器编码时,我选择使用枚举来表示武器的类型和稀有性。我已经为我的Weapon课编写了所有内容;然而,当我尝试创建一个Weapon对象时,我收到一个与我的枚举有关的错误 -error: 'common' is not a type。相关代码如下:

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

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);

当然,代码还在继续;但这是与我的错误相关的所有代码。最后,当我尝试创建一个Weapon对象时,出现错误:

#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

sword枚举也会发生同样的错误。我已经研究了这个问题,但我找不到与我遇到的问题类似的任何内容。任何帮助都非常感谢!

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

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;
};