一个子类继承多个父类时,在父类指针转化为子类指针以及子类指针转化为父类指针方面c++似乎做的很是智能化:

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 class A
 4 {
 5 public:
 6     A()
 7     {
 8 
 9     }
10     virtual void print()
11     {
12         cout << 1 << endl;
13     }
14 private:
15     int c;
16 };
17 
18 class C
19 {
20 public:
21     C()
22     {
23 
24     }
25 private:
26     int e[5];
27 };
28 
29 class B : public A, public C
30 {
31 public:
32     B() : A(), C()
33     {
34 
35     }
36     void print()
37     {
38         cout << 2 << endl;
39     }
40     void print2()
41     {
42         cout << 3 <<endl;
43     }
44 private:
45     int d[11];
46 };
47 int main()
48 {
49     A a;
50     B b;
51     a = b;
52     B *e = new B();
53     A *c = e;
54     C *f = e;
55     cout << "c:" << c << endl << "f:" << f << endl << "e:" << e << endl;
56     B *g = (B *)f;
57     B *h = (B *)c;
58     cout << "g:" << g << endl << "h:" << h << endl;
59     return 0;
60 }
View Code

程序运行结果如下:

1 c:0x22ddc20
2 f:0x22ddc2c
3 e:0x22ddc20
4 g:0x22ddc20
5 h:0x22ddc20

可以看见,子类指针转化为父类指针时,当父类指针需要偏移时可以自动偏移。同样的,父类指针转化为子类指针时也可以自动偏移到正确的位置,这说明在父类指针和子类指针转化过程中在地址偏移偏移方面完全不需要程序员操心。