【发布时间】:2015-02-04 23:40:01
【问题描述】:
我正在削减代码以使其更具可读性,我希望我不会让这变得难以理解。
class player : public character{
public:
// ---------stuff-------
protected:
// ------stuff--------
vector <item*> inventory;
};
class item {
public:
// -----stuff------------
virtual float getHealth(){};
virtual int getDef(){return 0;};
virtual int getAttAcc(){return 0;};
virtual int getAttPow(){return 0;};
virtual ~item();
protected:
string name;
string type;
int value;
int weight;
};
class weapon : public item{
public:
weapon(int attPow, int attAcc, int inValue, int inWeight, string inType, string inName);
weapon(const weapon& cWeapon);
int getAttAcc(weapon& weapon){return attAcc;};
int getAttPow(){return attPow;};
~weapon(){};
protected:
int attAcc;
int attPow;
};
当我需要武器(与库存中的指针一起存储)来访问其 attAcc 和 attPow 时,我的问题就出现了。
我尝试过的事情:
我尝试添加虚拟函数,然后用派生类更改它们。
我尝试将其排除在基类之外,但由于库存是指向项目的指针向量,因此不允许这样做。
最初我希望玩家有 2 个用于武器和盔甲的指针,但因为库存是一个不起作用的项目指针。
我为其他项目省略了我的课程,因为我确定一旦我弄清楚了其他项目是相同的。因为我有 3 个派生类,所以我需要库存作为指向基类的指针吗?
【问题讨论】:
-
见stackoverflow.com/questions/11855018/c-inheritance-downcasting你需要知道什么时候你需要以某种方式投射哪些对象。
-
我正在研究演员阵容,但我不太确定在这种情况下它会如何工作。是否可以使用铸造指针指向我的库存中的项目?我的意思是,如果库存[1] 是一种武器,我可以使用装箱点指向它以获取访问权限?
-
是的,但你在施法时需要确保它是武器。
标签: c++ pointers inheritance