使用dynamic_cast转换const类 [英] cast const Class using dynamic_cast

查看:118
本文介绍了使用dynamic_cast转换const类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想投放此内容:

class Base 
{
public:
    virtual ~Base(){};
};
class Der : public Base {};

int main()
{
    const Base* base = new Der;
    Der* der = dynamic_cast<Der*>(base); // Error

    return 0;
}

我该怎么办?
我试着放: const Der * der = dynamic_cast< Der *>(base); 来保存const,但这不起作用。

What should I do? I tried to put: const Der* der = dynamic_cast<Der*>(base); to mantain the const but this doesn't work.

推荐答案

尝试一下:

const Der* der = dynamic_cast<const Der*>(base);

dynamic_cast 没有能力删除 const 限定词。您可以使用 const_cast 分别丢弃 const ,但这通常在大多数情况下不是一个好主意。因此,如果您使用 dynamic_cast 捉住了自己,通常表明有更好的方法来完成您要尝试做的事情。这并不总是错误的,但可以将其视为警告您正在艰难地做事。

dynamic_cast doesn't have the ability to remove a const qualifier. You can cast away const separately using a const_cast, but it's generally a bad idea in most situations. For that matter, if you catch yourself using dynamic_cast, it's usually a sign that there is a better way to do what you are trying to do. It's not always wrong, but think of it as a warning sign that you are doing things the hard way.

这篇关于使用dynamic_cast转换const类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆