C++代码理解 (强制指针转换)

 1 #include<iostream>
 2 using namespace std;
 3 class A
 4 {
 5     public:
 6         A()
 7         {
 8             a=1;
 9             b=2;
10             c=4;
11             f=6;
12         }
13     private:
14         int a;
15         double b;
16         int c;
17         double f;
18 };
19 class B
20 {
21     public:
22         B()
23         {
24             d=3;
25             e=5;
26         }
27         void print()
28         {
29             cout<<e<<endl;
30             //cout<<sizeof(d)<<endl;
31             //cout<<sizeof(e)<<endl;
32         }
33     private:
34         int d;
35         double e;
36 };
37 int main(int argc, char* argv[])
38 {
39     A a;
40     B* pb= (B*)(&a);//这里必须要强制转换
41     //B pb;
42     (pb+0)->print()<<endl;
43     (pb+1)->print()<<endl;
44     //pb.print();
45     return 0;
46 }

以上代码输出:2 6,我的理解是第40行的操作让pb指向对象a的内存地址空间,且pb+1就相当于整个下移int与double的内存空间。

posted @ 2018-11-15 00:54  SuzanneHuang  阅读(294)  评论(0编辑  收藏  举报