如何从基类向量到达派生类变量?

时间:2017-06-07 09:05:20

标签: c++ inheritance vector

#include <iostream>
#include <vector>

class Entity
{
public:
    bool hinders_sight = false;
};

class Pillar : public Entity
{
public:
    bool hinders_sight = true;
};

int main()
{
    std::vector<Entity*> Entities;

    Pillar pillar;

    Entities.push_back(&pillar);

    std::cout << pillar.hinders_sight << std::endl;
    std::cout << Entities[0]->hinders_sight << std::endl;

    return 0;
}

pillar.hinders_sight返回true(应该如此)

Entities[0]->hinders_sight返回false

如何从hinders_sight到达pillar的{​​{1}}?

2 个答案:

答案 0 :(得分:3)

现在发生的事情是,派生类中有两个变量hinders_sight,一个来自基类,另一个来自派生类。

这里有两种主要方法可以解决这个问题(我不建议在你的基类和派生类中为同一个东西保留两个单独的变量),要么你可以使变量成为基类中的受保护/私有变量,然后根据需要提供获取和存储变量的函数,或者可以使get_hinders_sight()函数成为虚拟函数。

class Entity {
public:
    Entity(bool hinders_sight_in = false) 
        : hinders_sight{hinders_sight_in} {}
    bool get_hinders_sight() { return this->hinders_sight; }
private:
    bool hinders_sight = false;
};

class Pillar : public Entity {
public:
    Pillar() : Entity{true} {}
};

或者

class Entity {
public:
    virtual bool get_hinders_sight() { return false; }
};

class Pillar : public Entity {
public:
    bool get_hinders_sight() override { return true; }
};

答案 1 :(得分:2)

使用virtual bool HindersSight(){return hinders_sight;}因为变量不是虚拟的。

编辑:哦,让你的变量受保护或私有,以促进封装。你可以完成摆脱变量并为每个类实现HindersSight()直接返回true或false。

相关问题