1# include <iostream>
2using namespace std;
3
4class base
5{
6public:
7 base()
8 {
9 cout <<" base::val "<<endl;
10 val = 12345;
11 print();
12 }
13 base(int x)
14 {
15 val = x;
16 cout << " "<<endl;
17 }
18 virtual void print()
19 {
20 cout << " base:print(), val = "<<val<<endl;
21 }
22 base & operator = (int x)
23 {
24 val = x;
25 cout <<" base::operator, val = "<<x<<endl;
26 return *this;
27 }
28 void relase()
29 {
30 cout << " base::relase" <<endl;
31 }
32 ~base()
33 {
34 cout << " ~base::val = "<< val <<endl;
35 }
36protected:
37 int val;
38};
39
40class deiver:public base
41{
42public:
43 deiver()
44 {
45 cout << " deiver::val "<<endl;
46 }
47
48 deiver(int x)
49 {
50 val = x;
51 print();
52 }
53 void print()
54 {
55 cout << " deiver::print(), val = "<< val <<endl;
56 }
57 void relase()
58 {
59 cout << " deiver::relase, val = "<<val<<endl;
60 }
61 deiver & operator = (int x)
62 {
63 val = x;
64 cout <<" deiver::operator, val = "<<x<<endl;
65 return *this;
66 }
67 ~deiver()
68 {
69 cout << " deiver::~deiver "<<endl;
70 }
71};
72void des(base * b)
73{
74 b->print();
75 b->relase();
76}
77deiver de = 98765;
78int main()
79{
80 deiver * dee = new deiver;
81 *(base *)dee = 100;
82 des(dee);
83
84 return 0;
85}
86
输出结果。。。
因为de是全局变量,所以先调用基类构造函数,在调用子类的带int的构造方法。。
然后dee同理先基类构造函数,然后调用默认构造函数。
最后dee强制转换为基类指针进行复制,根据多态,调用基类的operator=方法
最后调用子类的print和父类的relase方法。
因为print是虚函数
运算结果为
base::val
base:print(), val = 12345
deiver::print(), val = 98765
base::val
base:print(), val = 12345
deiver::val
base::operator, val = 100
deiver::print(), val = 100
base::relase