1. 程式人生 > >C++程式碼理解 (強制指標轉換)

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的記憶體空間。