【问题标题】:Accessing child class members using pointer to a base abstact class, which can't be dynamic_cast使用指向基础抽象类的指针访问子类成员,该基础抽象类不能是 dynamic_cast
【发布时间】:2014-10-07 21:18:56
【问题描述】:

我有一个播放器类,有:

typedef string cptype;
map <cptype, unique_ptr<Cp> > Cps;

我添加了指向此地图的指针:

Cps.insert(make_pair("Pos", unique_ptr<Cp>(new PosCp())));

现在当我尝试使用这个访问 PosCp 的 pos 成员变量时:

Cps["Pos"]->pos = sf::Vector2f(0, 0);

我得到错误:

class Cp has no member pos

当我尝试使用dynamic_cast 时:

dynamic_cast<PosCp*>(Cps["Pos"])->pos = sf::Vector2f(0, 0);

我得到错误:

cannot dynamic_cast [this object]

(当然,我不想更改指针,我只想访问成员变量)

如何在不改变地图指针类型的情况下访问成员pos

这里是 CpPosCp 类:

class Cp
{
    public:
        Cp();
        virtual ~Cp();

        cptype type;
};

class PosCp : public Cp
{
    public:
        PosCp();
        ~PosCp();

        sf::Vector2f pos;
};

【问题讨论】:

    标签: c++ pointers dictionary inheritance dynamic-cast


    【解决方案1】:

    你可以试试这个:

    if (PosCp * p = dynamic_cast<PosCp *>(Cps["Pos"].get()))
    {
        p->pos = sf::Vector2f(0, 0);
    }
    else
    {
        // most-derived type of *Cps["Pos"] is not PosCp
    }
    

    【讨论】:

    • 更重要的是,这里的if有什么重要性?如果谓词失败会发生什么?
    • 颤抖 if 语句中的赋值 :(
    • @Yaxlat 然后它不指向 PosCp。发生什么取决于你。
    • @paulm:这里没有分配任何内容。
    • "if (PosCp * p = " 你能解释一下这不是作业吗?
    猜你喜欢
    • 2013-01-27
    • 1970-01-01
    • 2015-07-28
    • 2010-12-02
    • 2011-05-24
    • 1970-01-01
    • 2018-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多