简体   繁体   English

不能将dynamic_cast用于const对象

[英]Can not use dynamic_cast to a const object

I want to write a method where a Base object pointer will be passed as a parameter, and inside the method it will be casted to derived object pointer. 我想编写一个方法,其中Base对象指针将作为参数传递,并且在方法内部它将被转换为派生对象指针。

void func( const Base* const obj){
    Derived* der = dynamic_cast<Derived*>(obj);
}

But it shows error because dynamic cast cannot cast away const specifier . 但它显示错误,因为动态强制转换不能抛弃const说明符 But I am not understanding why const specifier has to be removed here, all I am doing is creating a derived pointer which should point to some offset amount after the base pointer. 但我不明白为什么必须在这里删除const说明符,我所做的只是创建一个派生指针,它应指向指针之后的一些偏移量。 I also tried const Derived* const der = dynamic_cast<Derived*>(obj); 我也试过const Derived* const der = dynamic_cast<Derived*>(obj); , but no result. ,但没有结果。

It is important to pass the parameter as const . 将参数作为const传递非常重要。 How can I do this? 我怎样才能做到这一点? Do I have to do it in the ugly way of first applying const_cast then dynamic_cast ? 我是否必须以丑陋的方式首先应用const_cast然后使用dynamic_cast is there any better way? 有没有更好的方法?

You're casting away const because you didn't do this: 你丢弃const因为你没有这样做:

const Derived* der = dynamic_cast<const Derived*>(obj);

If you actually need a Derived* then you need to 如果你真的需要Derived*那么你需要

Derived* der = dynamic_cast<Derived*>(const_cast<ObjType*>(obj));

What you cannot do is remove the const qualifier with a dynamic_cast . 你不能做的是用dynamic_cast 删除 const限定符。 If the types are polymorphic (have at least one virtual function) you should be able to do: 如果类型是多态的(至少有一个虚函数),你应该能够做到:

const Derived *der = dynamic_cast<const Derived*>(obj);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM