1 #include <iostream>
2 #include <string>
3 using namespace std;
4 class people
5 {
6 public:
7 string name;
8 int age;
9 virtual void print();
10 };
11
12 class teacher:public people
13 {
14 public:
15 int wage;
16 virtual void print();
17
18 };
19
20 void main()
21 {
22 people p1;
23 teacher t1;
24 t1.name="lili";
25 t1.age=31;
26 t1.wage=4200;
27 p1=t1;
28 p1.print();
29 cout<<endl<<endl;
30 t1.print();
31
32 }
33 void people::print()
34 {
35 cout<<name<<endl;
36 cout<<age<<endl;
37 }
38 void teacher::print()
39 {
40 cout<<name<<endl;
41 cout<<age<<endl;
42 cout<<wage<<endl;
43
44 }
派生类对象赋给基类对象合法,但派生类对象有、基类没有的数据成员(成员函数)在赋值过程中会丢失,即产生切割问题。
改为:
1 void main()
2 {
3 people *pp1;
4 teacher *pt1;
5 pt1=new teacher;
6 pt1->name="lili";
7 pt1->age=31;
8 pt1->wage=4200;
9 pp1=pt1;
10 pt1->print();
11 cout<<endl<<endl;
12 pp1->print();
13
14 }
数据成员没有丢失,但必须注意必须使用虚函数访问。基类people将print()声明为virtual,,所以一旦编译器看到以下调用就会检查people和teacher的virtual表,判断pp1是指向pt1类型的对象:pp1->print(),因此就会使用以下函数代码:teacher::print(),而不会去使用people::print()
的代码
时间: 2024-10-05 23:50:17