C++继承代码实现+细节解释

private与protected: 

区别:

派生之后,private对应的基类的私有数据成员在派生类当中是无法进行访问的,但protected对应的基类的私有数据成员在派生类当中是可以进行访问的。

共同点:

private与protected的数据成员都只能够在类内访问,类外无法访问,

#include<iostream>
#include<string>
using namespace std;
class Person
{
protected:
	string Name;//姓名
	int Age;//年龄
	int ID;//学号
private:;
public:
	Person(const string& Strname, const int StrAge = 18, const int StrID = 00000) : Name(Strname), Age(StrAge), ID(StrID){};
	void ShowInf()
	{
		cout << "个人类:" << endl;
		cout <<"姓名:"<< Name << endl; 
	cout <<"年龄:"<< Age << endl;
	cout << "学号:" << ID << endl << endl;
	};
	int GetAge(){ return Age; }




};
class Teacher:virtual public Person//虚基类继承
{public:
//派生类的构造函数
	Teacher(const string& Strname, const int StrAge = 18, const int StrID = 00000, const string& StrClass="计算机") :Class(StrClass), Person(Strname, StrAge, StrID){}
	void ShowInf()
	{
		cout << "教师类:" << endl ;
		cout << "姓名:" << Name << endl;
		cout << "年龄:" << Age << endl;
		cout << "学号:" << ID << endl;
		cout << "教授课程:" << Class << endl << endl;

	};
protected:
	string Class;//教授课程名字


};

class PostgraguateStudent :virtual public Teacher
{
public:
	PostgraguateStudent(const string& Strname, const int StrAge = 18, const int StrID = 00000, const string& StrClass = "计算机", const string StrGrade = "二") :Grade(StrGrade), Teacher(Strname, StrAge,StrID,StrClass), Person(Strname, StrAge, StrID){}
	void ShowInf()
	{
		cout << "研究生类:" << endl ;
		cout << "姓名:" << Name << endl;
		cout << "年龄:" << Age << endl;
		cout << "学号:" << ID << endl;
		cout << "教授课程:" << Class << endl;
		cout << "所在年级:" << Grade << endl;
	};
private:
	string Grade;//所在年级


};
int main(int argc, char* argv[])
{
	Person person("shun",18,20231234);
	person.ShowInf();
	
	Teacher teacher("shun");
	teacher.ShowInf();
	
	PostgraguateStudent postgraguateStudent("xiaoming");
	postgraguateStudent.ShowInf();//对基类当中的同名函数进行了隐藏
	system("pause");
	return 0;
}

运行结果:

个人类:
姓名:shun
年龄:18
学号:20231234

教师类:
姓名:shun
年龄:18
学号:0
教授课程:计算机

研究生类:
姓名:xiaoming
年龄:18
学号:0
教授课程:计算机
所在年级:二
请按任意键继续. . .



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值