保护继承----没啥难的

任务描述

本关任务:采用保护继承设计学生信息类。

相关知识

为了完成本关任务,你需要掌握保护继承的使用。

保护继承
保护继承相对于公有继承,访问性有所降低,父类的公有成员在子类中变成了保护成员,也就无法在外部通过一个对象访问父类成员了,但是对于这个子类的子类仍然是可见的(因为可见性只是降到了 protected )。

如果要保护继承一个类,只需继承时在类名前面加上 protected 关键字即可。

例如:

class Base
{
public:
int A;
};
class D1 : protected Base // 保护继承 Base 类
{
/* …… */
};
int main()
{
D1 d;
d.A = 10; // 尝试访问 D1 的基类 Base 中的 A 成员,但是由于是保护继承,所以这样做是错误的。
}
在保护继承中如果想通过子类访问父类的成员,那就只能在子类中增加一些 get 、set 函数来实现了。

例如:

/* Base类的定义同上 */
class D1 : protected Base
{
public:
void SetA(int a); // 设置 Base 类中 A 的值
int GetA(); // 获取 Base 类中 A 的值
};
void D1::SetA(int a)
{
A = a;
}
int D1::GetA()
{
return A;
}
int main()
{
Student st;
st.SetA(10); // 将 Base 类的 A 成员设置为 10
}

编程要求

在右侧编辑器中的Begin-End之间补充代码,采用保护继承设计学生信息类,并实现 Set 和 PrintSID 函数,具体要求如下:

Student 类公有成员函数:void PrintSID(),函数输出成员变量 SID 的值,输出格式为:学号:SID。

普通函数:Set(int sid,string name,Student *ptr),它用前两个参数设置 ptr 对象的 SID 和 Name(继承 People 拥有的属性)属性值。

现在已有一个基类 People,它有一个公有成员变量姓名 Name,一个公有成员函数 PrintName(函数的功能是打印出 Name 的值)。

class People
{
public:
string Name;
void PrintName();
};
void People::PrintName()
{
cout << “姓名:” << Name << endl;
}

测试说明

平台会对你编写的代码进行测试,比对你输出的数值与实际正确数值,只有所有数据全部计算正确才能通过测试:

测试输入:1 严宏富

预期输出:

学号:1
姓名:严宏富
下面展示一些 代码

#include "people.h"     // People 类定义在这里面
#include <string>
#include <iostream>
using namespace std;

/**********  Begin **********/
//保护继承 People
class Student:protected People
{
	public:
		int SID;
		void PrintSID();
    	//添加一个 Set 函数来设置父类的 Name 成员
    	friend void Set(int sid,string name,Student *ptr);
};

/********* End *********/

void Student::PrintSID()
{
    /********* Begin *********/
    //输出学号 SID
    cout << "学号:" << SID << endl;
    /********* End *********/
}

void Set(int sid,string name,Student *ptr)
{
    /********* Begin *********/
    //给 ptr 对象的两个属性赋值
    ptr->SID=sid;
    ptr->Name=name;
    /********* End *********/
}





#ifndef PEO_H_
#define PEO_H_

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

class People
{
	public:
		string Name;
		void PrintName();
};

void People::PrintName()
{
    cout << "姓名:" << Name << endl;
}
#endif


#include "usr.h"

int main()
{
	int id; 
	string name;
	cin >> id >> name ;
    Student st;
    Set(id,name,&st);
    st.PrintSID();
	((People*)&st)->PrintName();
}

  • 5
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值