C++ 面向对象 - 类的继承与派生

第一题:公有继承 —— 学生信息类

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

using namespace std;

/**********  Begin **********/
//公有继承 People
class Student:public People
{
	public:
		int SID;
        void  PrintSID();
};
/**********  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 *********/
}

第2题:保护继承 —— 学生信息类

#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 id,string name,Student *ptr);

};

/********* End *********/
void Student::PrintSID()
{
    /********* Begin *********/
    //输出学号 SID
    cout<<"学号:"<<SID<<endl;
    
    
    /********* End *********/
}
void Set(int id,string name,Student *ptr)
{
    /********* Begin *********/
    //给 ptr 对象的两个属性赋值
    ptr->SID=id;
    ptr->Name=name;
    
    
    /********* End *********/
}

第三题:研究生信息类

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

/********* Begin *********/
//私有继承 People 类
class Student :private People
{
	public:
		int SID;
		void PrintSID();
		//添加一个 Set 函数来设置父类的 Name 成员
		 void SetName(string name);
};

/********* End *********/
void Student::SetName(string name)
{
    Name=name;
}

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


/********* Begin *********/
// 公有继承 Student 类
class Graduate:public Student
{
	public:
		int ResearchID;
		void PrintResearchID();
		//添加一个 Set 函数来设置父类的 SID 成员
    friend void	Set(string name,int sid,int rid,Graduate *ptr);
		//添加一个 Set 函数来调用父类的 SetName 函数
        void Set(string name);
};

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

void  Graduate::Set(string name)
{
    SetName(name);
}
void Graduate::PrintResearchID()
{
    /********* Begin *********/
    //输出研究方向 ResearchID
    
    cout<<"研究方向:"<<ResearchID<<endl;
    
    /********* End *********/
}
//添加一个 Set 函数来设置父类的 SID 成员
//它用前三个参数设置 ptr 所指对象的三个成员。
void Set(string name,int sid,int rid,Graduate *ptr)
{
    /********* Begin *********/
    //设置 ptr 所指对象的三个成员
    ptr->SID=sid;
    ptr->ResearchID=rid;
    ptr->Set(name);
    
    
    /********* End *********/
}

  • 6
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值