C++之继承

#include <iostream>

using namespace std ; 

class  Animal
{
	private:
		int age ;

	protected:
		int id ; 
	
	public:
		int Height ; 
		void Say_hi(void)
		{
			cout << "this is hello" <<endl ; 
		}
};

//无论哪种继承,父类私有成员在子类不可访问
//公有继承,父类的公有跟受保护权限到了子类权限不变
//受保护继承,父类的公有成员变成子类的受保护成员,受保护成员权限不变
//私有继承,父类的公有成员及父类的受保护成员变成子类的私有成员

class People : public  Animal
{	
	private:
		int aa ; 	
	
	protected:
	int cc ; 
	
	public :
	int a ; 
	
	void Say_hi(void)
	{
		cout << "hi " << endl ;
	}

	void Say_cc(void)
	{
		cout << "cc : " << cc << endl ;
		cout << "id : " << id << endl ; 
		//cout << "age : " << age << endl ; 
		cout << "aa : " << aa << endl ; 
	}
};

int main(void)
{

	People  pp ; 
//	pp.Height = 100 ;
//	pp.Say_cc();
//	pp.cc = 200 ;    //受保护的变量不允许直接访问
//	pp.id = 200 ; 
//	pp.Say_hi();

	pp.Say_hi();
	//两者皆可
	pp.Animal::Say_hi();
	pp.People::Say_hi();

	return 0 ; 
}

运行结果:

再来看一个代码,体现了继承性。

#include <iostream> 
using namespace std ;

class Human
{
	public:
	int age ;
	int sex ;
	void set_age(int age)
	{
		this->age = age ;
	}
	void set_sex(int sex)
	{
		this->sex = sex ;
	}
};

class Student : public Human
{
	public:
	int a ; 
	int b ; 
	int c ;
	void set_abc(int a,int b , int c)
	{
		this->a = a ; 
		this->b = b ; 
		this->c = c ;
	}
};


int main(void)
{
	Student s ;
	s.set_abc(100,200,300);
	s.Human::set_age(100);
	s.Human::set_sex(0);
	printf("age=%d sex=%d a=%d b=%d c=%d\n", \
		s.Human::age,	\
		s.Human::sex,	\
		s.a,s.b,s.c);	
	return 0 ;
}
Human类拥有成员,Student类继承了Human的成员,同时它扩展了自己的成员,所以,Human有的东西Student可以不用写,直接引用即可。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Engineer-Bruce_Yang

谢谢您

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值