cast

今天在abp上看到篇关于cast的文章,有些问题我还没注意到。
=1=
// cast_a.cpp
#include <iostream>
using namespace std;

class Interface
{
    int member;
};

class Base {};

class Derived : public Interface, public Base {};

int main()
{
    Base* b = (Base*)100;
    Derived* d1 = reinterpret_cast<Derived*>( b );
    Derived* d2 = static_cast<Derived*>( b );

 cout << "b: " << b << endl;
 cout << "d1: " << d1 << endl;
 cout << "d2: " << d2 << endl;
}
---------------------------------------------------------
b: 00000064
d1: 00000064
d2: 00000060
----------------------------------------------------------

小小改变一点,结果就不一样咯8)
//cast_b.cpp

#include <iostream>
using namespace std;

class Interface
{
    int member;
};

class Base {};

class Derived : public Interface, public Base {};

int main()
{
    Base* b = (Base*)100;
    Derived* d1 = reinterpret_cast<Derived*>( b );
    Derived* d2 = static_cast<Derived*>( b );

 cout << "b: " << b << endl;
 cout << "d1: " << d1 << endl;
 cout << "d2: " << d2 << endl;
}
---------------------------------------------------------
b: 00000064
d1: 00000064
d2: 00000064
----------------------------------------------------------
==WHY?==
Derived对象在内存中的分布分别如下:
cast_a.cpp                cast_b.cpp
-----------                ----------- <-- b
| Interface |                |    Base    |
-------------  <-- b       -------------
|    Base    |                | Interface |
-----------                -----------
reinterpret_cast很简单,只是把指针对应的二进制数值传递给左边。
但static_cast会“根据相关类型信息来做转换,如果可能,对 b 指针做一些偏移”(引用的8)。
而在这个例子里,a时,由于Base并不是第一个子类,所以,static_cast会做一些偏移,把指针偏移到Derived的开始位置。而bBase就是第一个子类,base本来就和derived位置相同,所以static_cast的结果还是指向原来位置,换句话就是,偏移为0。

------------------------------------------------------------------------------------
p.s.
不要只专注于细节,而废弃掉学习如何思考

 

有问题!原来怎么写得啊

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值