c++ - 基类指针,访问派生类成员变量?

标签 c++ pointers inheritance

我正在削减代码以使其更具可读性我希望我不会让它难以理解。

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 时,我的问题就来了。
我试过的事情: 我尝试添加虚函数,然后用派生类更改它们。

我尝试将其排除在基类之外,但由于库存是指向项目的指针 vector ,因此不允许这样做。

最初我希望玩家有 2 个武器和盔甲指针,但因为库存是一个不起作用的元素指针。

我为其他项目省略了我的类(class),因为我确定一旦我弄明白了其中一个,其他项目都是一样的。因为我有 3 个派生类,所以我需要将 list 作为指向基类的指针,对吧?

最佳答案

不确定,你想在这里做什么。

如果你想使用虚函数,最好在派生类中也使用virtual关键字。

但是,虚函数必须有相同的参数(又名签名),否则它只会重载基类函数,虚函数机制将无法工作。

在您的示例中,函数 int weapon::getAttAcc(weapon& weapon) 不会覆盖基类 int item::getAttAcc(),因为初始函数没有参数。

您可以向 int item::getAttAcc(weapon& weapon) 添加一个参数,如果这是您想要的话。

另一种解决方案是添加类型函数:

class Item {
   public:
     virtual int getItemType() = 0; // this will make function pure virtual
};

class Weapon : public Item {
   public:
     virtual int getItemType() { return 1; }
     int getAttAcc() {return attAcc;}
}

Item * item = // something
if (item.getItemType() == 1) // weapon
{
   Weapon * weapon = (Weapon)item;
   weapon->getAttAcc();
}

或者,正如其他评论员所建议的那样。更多 C++ 方式:

// cast will be successful only for Weapon type object.
if (Weapon * weapon = dynamic_cast<Weapon *>(item)) { // weapon
    weapon->getAttAcc();
}

关于c++ - 基类指针,访问派生类成员变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27338979/

相关文章:

java - 从类继承以获取输出。

c++ - 包含STL头文件的问题

c++ - 构建失败错误 : Cannot build C++ SDK Helloworld with qibuild

c++ - 调试断言失败。表达式映射迭代器不可取消引用

c++ - const 指针作为类字段赋值

c++ - 如何将指向 PVOID 的指针类型的参数从 LabView 传递到 DLL?

oop - 可以采用哪些方法来使用组合而不是继承?

python - 使用父类定义的方法时出错

c++ - base-R seq 的 Rcpp 版本丢弃值

c++ - 为什么重载 operator<< 来打印 Eigen 类成员会导致段错误?