static_cast and dynamic_cast?

ajoo 2002-05-16 02:02:16
what is the difference between
static_cast<A*> (p)
and
(A*)p
?
does C++ put some type info in the memory for dynamic_cast to work?
...全文
86 16 打赏 收藏 转发到动态 举报
写回复
用AI写文章
16 条回复
切换为时间正序
请发表友善的回复…
发表回复
caoxin 2002-05-18
  • 打赏
  • 举报
回复
how dynamic_cast can know the type info at runtime:

看《Inside C++ Object Model》书上有
sbg 2002-05-18
  • 打赏
  • 举报
回复
static_cast是最普通的转换,之能用于内建类型。比如:int转换成double。
const_cast最普通的用途就是转换掉对象的const属性
dynamic_cast把指向基类的指针或引用转换成其派生类或兄弟类的指针或引用
reinterpret_cast最普通的用途就是在函数类型指针之间进行转换 最不常用
SlaSk 2002-05-18
  • 打赏
  • 举报
回复
static_cast是在编译其进行类型校验的,因此只支持上溯造型。

补充:对于无法确定的转化就用它。

dynamic_cast在运行时通过RTTI进行类型判断,可以进行下塑造性。
ajoo 2002-05-17
  • 打赏
  • 举报
回复
I think i'm pretty clear about their usage now.
But what I'm wondering is that how dynamic_cast can know the type info at runtime. what is it's runtime scheme?
greening 2002-05-17
  • 打赏
  • 举报
回复
你可以看一下effective c++,四种转换。我想你就清楚很多了。
static_cast是最普通的转换,比如:int转换成double。
const_cast最普通的用途就是转换掉对象的const属性,详见第21条款。
dynamic_cast把指向基类的指针或引用转换成其派生类或兄弟类的指针或引用,详见第39条款。
reinterpret_cast最普通的用途就是在函数类型指针之间进行转换。




mylove0618 2002-05-16
  • 打赏
  • 举报
回复
dynamic_cast的目的是在类层次结构中提升一个对象,别提升的对象必须是被强制转换的类型的直接或间接继承。之所以称为提升,是因为在层次结构中,基类比较接近层次的根,因此强制转换成基类就是其在结构中向上移动。如果dynamic_cast使用引用而不是指针,eg:dynamic_cast<R&>(p).并且引用不是类型p的直接或间接类,那么dynamic_cast就会发生一个bad_cast异常。
ajoo 2002-05-16
  • 打赏
  • 举报
回复
polarislee(北极星):
c=static_cast<B*>(b) should work.
canco 2002-05-16
  • 打赏
  • 举报
回复
看《C++语言的设计和演化》关于“强制”的这一章,里面有完整的阐述。
北极猩猩 2002-05-16
  • 打赏
  • 举报
回复
static_cast是在编译其进行类型校验的,因此只支持上溯造型。
dynamic_cast在运行时通过RTTI进行类型判断,可以进行下塑造性。
如:
class A{};
class B:public A{};

A* a=new A();
A* b=new B();
B* c;
c=static_cast<B*>(b) //error
c=dynamic_cast<B*>(b) //OK

如果dynamic_cast发现非法转换会返回NULL
ajoo 2002-05-16
  • 打赏
  • 举报
回复
the problem is, if you have a
const char* p = "hello"+1;
how can typeid(p) work? how does it know where to get the type info? p should definitely points to 'e' in this case.
saucer 2002-05-16
  • 打赏
  • 举报
回复
I could guess some additional bytes were allocated at that memory address which are RTTI related, for example, these bytes could point to some global type table
ajoo 2002-05-16
  • 打赏
  • 举报
回复
well. conceptually, yes.
But how? if the pointer is pointing to the memory address, how can it know the real type of the object?
saucer 2002-05-16
  • 打赏
  • 举报
回复
run-time type information (RTTI):
typeid, type_info

ajoo 2002-05-16
  • 打赏
  • 举报
回复
faint!
I should have searched csdn first.
seems static_cast supports downcast, but not stupidcast.
if A is not super type of B, B is not super type of A,
then it fails.
but does anybody know how dynamic_cast get the type info?
ajoo 2002-05-16
  • 打赏
  • 举报
回复
hey, Kaye(菜菜狗)
what does "gz" mean?
I'm a newbie of csdn.
Kaye 2002-05-16
  • 打赏
  • 举报
回复
gz

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧