使用 dynamic_cast 强制转换 const 类

2022-01-23 00:00:00 constants c++ dynamic-cast

我想投这个:

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(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.

相关文章