【C++】继承

继承语法

继承方式只会缩小成员的访问权限

#include<iostream>
#include<string> 
using namespace std;
//基类
class father
{
private:
	int pri;
protected:
	int pro;
public:
	int pub;
	void fun() { cout << "fun()" << endl; }
	void eat() { cout << "eat()" << endl; }
};
//派生类
class son :public father
{
	void work()
	{
		pri = 1;//报错。父类私有成员不能再子类中访问
		pro = 1;//父类受保护的成员可以在子类访问
		pub = 1;//父类公有成员可以再子类访问
	}
};

int main() {
     //父类有的子类有,父类没有的,子类也可以有,因为可以单独写。
	son s;
	s.pub;
	s.fun();
	s.eat();
	return 0;
}

继承方式

凡是基类中私有的,派生类都不可访问。

●基类中除了私有的成员,其他成员在派生类中的访问属性总是以(继承方式,基类的访问属性)中安全性高的方式呈现。(安全性级别:私有>保护>公有)

private:

#include<iostream>
#include<string> 
using namespace std;

class father 
{
public:
	int pub;
protected:
	int pro;
private:
	int pri;
};

class son :private father 
{
	void fun()
	{
		pri = l; //报错.父类中私有成员变量不能再子类中访问
		pro = 1; //pro在son中可以被访问,但是访问属性是private
		pub = 1;//pub在son中可以被访问,但是访问属性是private
	}
};

class grandSon :public son
{
	void fun() {
		//因为son中pub 和pro 的访问属性均被修改为private所以不能再grandSon中访问
		pub = 1;//报错.
		pro = 1;//报错.
	}
};
int main()
{
	son s;
	s.pub = 1; //报错,因为子类中改变了属性,变成private
	return 0;
}

protected:

#include<iostream>
#include<string> 
using namespace std;

class father
{
public:
	int pub;
protected:
	int pro;
private:
	int pri;
};

class son :protected father
{
	void fun()
	{
		//凡是基类中私有的,派生类都不可访问。
		pri = l; //报错.pri不能在son中访问
		pro = 1; //protected
		pub = 1;//protected
	}
};

class grandSon :public son
{
	void fun() {
		//确定是受保护的,因为私有的不能在子类中访问
		pub = 1;
		pro = 1;
	}
};
int main()
{
	son s;
	//因为在son中 pub和pro是 protected
	s.pub = 1; //报错
	s.pro = 1;//报错
	return 0;
}

public:

#include<iostream>
#include<string> 
using namespace std;

class father
{
public:
	int pub;
protected:
	int pro;
private:
	int pri;
};

class son :public father
{
	void fun()
	{
		//凡是基类中私有的,派生类都不可访问。
		pri = l; //报错.pri不能在son中访问
		pro = 1; //protected  son的对象不能访问pro son的子类可以
		pub = 1;//public  son的对象能访问pub
	}
};

class grandSon :public son//子类
{
	void fun() {
		//确定是受保护的,因为私有的不能在子类中访问
		pub = 1;
		pro = 1;
	}
};
int main()
{
	son s;//对象
	//因为在son中 pub和pro是 protected
	s.pub = 1; 
	s.pro = 1;//报错
	return 0;
}

多继承

一个类可以继承自多个父类,他可以从多个基类继承数据和函数。定义一个派生类,我们使用一个类派生列表来指定有哪些基类代码如下:

#include<iostream>
#include<string> 
using namespace std;
//会出现两个变量的名称相同,用命名空间解决
class father
{
public:
	int pub;
};

class mother
{
public:
	int pub;
};

class son :public father, public mother
{

};
//二义性  问题用作用域解决  作用域一般加在名字前面
int main() {
	son s;
	s.father::pub = 1;
	s.mother::pub = 1;
    return 0;
}

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值