1 #include <iostream>
2 using namespace std;
3
4 //子类同名函数覆盖父类
5 //父类指针存储子类地址,在有虚函数情况会调用子类方法,否则会调用父类方法
6
7 class base
8 {
9 public:
10 virtual void show()
11 {
12 cout << "base show" << endl;
13 }
14 };
15
16 class baseX : public base
17 {
18 public:
19 void show()
20 {
21 cout << "baseX show" << endl;
22 }
23 };
24
25 void main()
26 {
27 base *p1 = new baseX;
28 p1->show();
29 cout << typeid(p1).name() << endl;
30 //typeid会自动进行类型转换
31 //用子类进行初始化,有虚函数,*p1是baseX类型,没有虚函数则是base类型
32 cout << typeid(*p1).name() << endl;
33
34 //把父类转化为子类
35 //dynamic_cast主要用于多态的转换,如果没有虚函数,则不能把 通过
36 //子类初始化的父类 转化为子类
37 //dynamic_cast只能转化指针或者引用,不可以转化对象
38 baseX *px = dynamic_cast<baseX *>(p1);
39 px->show();
40 cin.get();
41 }