开发者

cast const Class using dynamic_cast

开发者 https://www.devze.com 2023-01-13 15:27 出处:网络
I want to cast this: class Base { public: virtual ~Base(){}; }; class Der : public Base {}; int main() { const Base* bas开发者_如何学Ce = new Der;

I want to cast this:

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

int main()
{
    const Base* bas开发者_如何学Ce = new Der;
    Der* der = dynamic_cast<Der*>(base); // Error

    return 0;
}

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


Try this:

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

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.


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

Der* der2 = dynamic_cast<Der*>(const_cast<Base*>(base));

while both the above castings work, the second one should be avoided.

0

精彩评论

暂无评论...
验证码 换一张
取 消