虚函数和static_cast [英] virtual functions and static_cast

查看:148
本文介绍了虚函数和static_cast的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,或者是UB,在多态类上使用static_cast之后,我可以安全地调用虚函数吗?

Can i safely call virtual functions after using static_cast on polymorphic class in situations like in the following code or is it UB?

#include <iostream>

class Base
{
public:
   virtual void foo() { std::cout << "Base::foo() \n"; }
};

class Derived : public Base
{
public:
   virtual void foo() { std::cout << "Derived::foo() \n"; }
};

int main()
{
   Base* derived = new Derived;
   Derived* _1 = static_cast<Derived*>(derived);
   _1->foo();
}


推荐答案

虽然我没有看到在你的具体例子这样做的要点。只需调用它

Yes, you can. Although I don't see the point of doing that in your specific example. Just calling it as

derived->foo();

没有任何转换将产生完全相同的效果。也就是说在这种情况下,某些类型的 static_cast 将由虚拟调用机制隐式执行。

without any casts would have produced exactly the same effect. I.e. some sort of static_cast in that case would be performed implicitly by the virtual call mechanism.

请注意, c $ c> static_cast 不会以任何方式抑制调用的虚拟性质。

Note that your static_cast does not in any way suppress the "virtual" nature of the call.

这实际上让我想知道你的问题真的是。你为什么会问这个问题?你想做什么?在你的代码示例中真正代表你想做什么?

That actually makes me wonder what your question is really about. Why would you even ask about it? What are you trying to do? In your code sample really representative of what you are trying to do?

这篇关于虚函数和static_cast的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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