dynamic_cast of void * [英] dynamic_cast of void *

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

问题描述

我需要使用动态转换void *

I need to use dynamic cast void*

void *target = (MYClass*)target;//I am storing initially(to implment delegate mechanism)
....
delegateClass *delegate = dynamic_cast<delegateClass*>(target);

这是给错误不能转换void *,我不能使用下面的代码...因为它是一个委托机制

It is giving error cannot convert void*, I cannot use below code... since it is a delegate mechanism

delegateClass *delegate = dynamic_cast<delegateClass*>(((MYClass*))target);

如何获取目标类型和实现...如果我使用typeid类的名称,但是如何在上面的方程中使用typeid而不是(((MYClass *))target)。

How to get the type of target and implement... If i use typeid() i can get the name of the class but how to use typeid in the above equation instead of (((MYClass*))target).

推荐答案

除非变量的原始类型有一个vtable(即,有虚函数),否则不能使用动态转换。这是因为dynamic_cast需要运行时类型信息,它记录在vtable中;如果vtable缺失,编译器不知道对象是什么类型。

You cannot use dynamic cast unless the original type of the variable had a vtable (ie, had virtual functions). This is because dynamic_cast requires run-time type information, which is recorded in the vtable; if the vtable is missing, the compiler doesn't know what type the object is.

你应该声明一个带有虚拟析构函数的基类,并使用指向这个基类的指针而不是 void *

You should declare a base class with a virtual destructor, and use pointers to this base class rather than void *.

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

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