基类与派生类的转换

 1 #include <iostream>
 2 #include <string.h>
 3 /* run this program using the console pauser or add your own getch, system("pause") or input loop */
 4 using namespace std;
 5 
 6 class Student
 7 {
 8     public:
 9         Student(int,string,float);
10         void display();
11     private:
12         int num;
13         string name;
14         float score;
15 };
16 
17 Student::Student(int n,string nam,float s)
18 {
19     num=n;
20     name=nam;
21     score=s;
22 }
23 
24 void Student::display()
25 {
26     cout<<endl<<"num:"<<num<<endl;
27     cout<<"name:"<<name<<endl;
28     cout<<"score:"<<score<<endl;
29 }
30 
31 class Graduate:public Student
32 {
33     public:
34         Graduate(int,string,float,float);
35         void display();
36     private:
37         float pay;
38 };
39 Graduate::Graduate(int n,string nam,float s,float p):Student(n,nam,s),pay(p){
40     
41 }
42 void Graduate::display()
43 {
44     Student::display();
45     cout<<"pay="<<pay<<endl;
46 }
47 int main(int argc, char** argv) {
48     Student stud1(1001,"li",99);
49     Graduate grad1(2001,"wang",99,443);
50     Student *pt=&stud1;
51     pt->display();
52     pt=&grad1;
53     pt->display();
54     return 0;
55 }
原文地址:https://www.cnblogs.com/borter/p/9405488.html