#include <iostream> using namespace std; class CPeople { public: void do_Thing1(){cout<<"CPeople do_thing1!"<<endl;}; virtual void do_Thing2(){cout<<"CPeople do_thing2!"<<endl;}; //virtual void do_Thing() = 0; //帶純虛函數的類叫做純虛類,純虛類不可實例化,其派生類若不實現該虛函數則仍爲虛類 static void pr(){cout<<"CPeople static!"<<endl;}; static int sex; void People(){ cout<<"people"<<age<<endl;}; void func(){cout<<"void func() CPeople"<<endl;}; private: protected: int age; }; class CStudent:public CPeople { public: void do_Thing1(){cout<<"CStudent do_thing1!"<<endl;}; void do_Thing2(){cout<<"CStudent do_thing2!"<<endl;}; //static void pr(){cout<<"CStudent static pr!"<<endl;}; //允許聲明定義,表面CStudent類有自己的static pr() void pr(){cout<<"CStudent pr!"<<endl;}; //允許聲明定義,表面CStudent類有自己的非staitc pr(),覆蓋基類static void pr() void Student(){ cout<<"student"<<age<<num<<endl;}; void set_param(int _age, int _num) { age = _age; num = _num; } void func(int a){cout<<"void func(int a) CStudent"<<endl;}; protected: int num; }; class CGrade:public CStudent { public: void do_Thing1(){cout<<"CGrade do_thing1!"<<endl;}; void do_Thing2(){cout<<"CGrade do_thing2!"<<endl;}; void Grade(){ sex = 3; cout<<"grade"<<age<<num<<grade<<endl;}; void set_param(int _age, int _num, int _grade) { age = _age; num = _num; grade = _grade; } private: int grade; }; int CPeople::sex = 2; //int CStudent::sex = 2; //可在派生類初始化,但是編譯器警告 int main(int argc, char* argv[]) { CGrade *gd = NULL; CPeople *pp = NULL; CStudent* sd = new CStudent(); gd = static_cast<CGrade*>(sd); pp = static_cast<CPeople*>(sd); sd->set_param(2,2); gd->set_param(1,2,3); sd->Student(); //輸出student12 說明gd指針指向CStduent對象空間 //sd->func(); //error:如果派生類重定義了重載成員,則通過派生類型只能訪問派生類中重定義的那些成員。 sd->func(1); gd->People(); //派生類指針接收基類對象指針,可以訪問基類方法 gd->do_Thing1(); //能調用CGrade的do_thing1 ? //gd->do_Thing2(); //將出錯,CGrade的do_thing2未實現 gd->Grade(); //能調用Grade()?爲什麼? 這一段函數的空間哪裏來的? //pp->Student(); //基類指針接收派生類對象指針,無法訪問派生類方法? “Student”: 不是“CPeople”的成員 pp->do_Thing1(); //調用CPeople的do_Thing1(); pp->do_Thing2(); //仍然調用CStudent的do_thing2,虛函數的調用之和new處理的對象有關,new出來的是誰的對象就調用誰的方法 sd->People(); //調用繼承過來的方法 sd->Student(); CPeople::pr(); //CStudent::pr(); sd->pr(); CPeople* pp1 = new CGrade(); pp1->do_Thing1(); // 非虛函數,調用接收指針的類方法 CPeople::do_Thing1() pp1->do_Thing2(); // 虛函數,調用new對象的方法 CStudent* dg2 = new CGrade(); dg2->do_Thing1(); // 非虛函數,調用接收指針的類方法 CStudent::do_Thing1() dg2->do_Thing2(); // 虛函數,調用new對象的方法 return 0; }筆者不解上述註釋含?的兩句代碼,望讀者大神指教