C++之类的继承和多态

 
#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;
}

笔者不解上述注释含?的两句代码,望读者大神指教

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值