C++之类的继承和多态

来源:互联网 发布:北京阿里云可用区a 编辑:程序博客网 时间:2024/05/16 14:16
#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;}
笔者不解上述注释含?的两句代码,望读者大神指教
原创粉丝点击