1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
#include <iostream> #include <string> using namespace std; class Student { public: Student(int ,string, float); void display(); private: int num; string name; float score; }; Student::Student(int n,string nam,float s) { num=n; name=nam; score=s; } void Student::display() { cout<<endl<<"num: "<<num<<endl; cout<<"name: "<<name<<endl; cout<<"score: "<<score<<endl; } class Graduate : public Student { public: Graduate (int ,string , float,float); void display(); private: float wage; }; Graduate ::Graduate(int n,string nam,float s,float w):Student(n,nam,s),wage(w){} void Graduate ::display() { Student ::display(); cout<<"wage= "<<wage<<endl; } int main() { Student stud1(1001,"Li",87.5); Graduate grad1(2001,"wang",98.5,1000); Student *pt=&stud1;//这里pt指针指向student类对象stud1, pt->display(); pt=&grad1;//由于pt指向student类,所以这里pt指向的是grad1中从基类student中继承的部分。 pt->display(); //总结,通过指向基类对象的指针,只能访问派生类中的基类成员,而不能访问派生类增加的成员; } |