c++ - 如何从基类 vector 到达派生类变量?

标签 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

如何从 vector 到达 pillarhinders_sight

最佳答案

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

这里有两种主要方法可以解决这个问题(我不建议在基类和派生类中为同一事物保留两个单独的变量),或者您可以使变量成为基类中的 protected /私有(private)变量,并且然后根据需要提供获取和存储变量的函数,或者您可以使 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; }
};

关于c++ - 如何从基类 vector 到达派生类变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44408192/

相关文章:

c++ - 使用 std::vector 在类中分配索引

c++ - 替换少量字节时如何在大字节数组上重新计算 CRC32

python - 在继承的 TreeView 中创建和打开记录在 odoo 中不起作用

CSS 不会覆盖继承的值

c++ - 如何将 std::vector::emplace_back 用于 vector<vector<int>>?

c++ - unistd read() 不起作用

c++ - 用 vector 的 vector 的元素初始化 vector 的空 vector

c++ - 如何在 DirectX 11 中导入 .obj 文件

c++ - 应用程序无法从 WinSxS 加载 Win32 程序集

c++ - 什么是对象切片?