简单的继承模版

#include <iostream>
#include <cstring>
#include <string.h>
using namespace std;
//基类有学生的名字,年龄,性别
class CPerson
{
public:

	CPerson(char *name, int age, char sex = 'M') //构造函数初始化成员函数
	{
		strncpy(this->name, name, 20);
		this->age = age;
		this->sex = sex;
	}
	void SetNameAndSex(char *name, char sex = 'M') //修改名字和性别
	{
		strncpy(this->name, name, 20);
		this->sex = sex;
	}
protected:
	void SetAge(int age) //修改年龄
	{
		this->age = age;
	}
	void ShowInfo() //显示
	{
		cout << "姓名:" << name << endl;
		cout << "性别:" << (sex == 'M' ? "男" : "女") << endl;
		cout << "年龄:" << age << endl;
	}
private:
	char name[20];
	char sex;
	int age;
};
//派生类有成绩,平均分,总分,继承基类成员函数及属性
class CStudent: public CPerson
{
public:
	CStudent(char *name, char *no, int age, char sex = 'M') :
			CPerson(name, age, sex)//调用基类构造函数来设定基类数据成员的初值,通常派生类中的基类成为基类拷贝或基类子对象
	{
		strncpy(this->stuno, no, 20);
	}
	void SetScore(float s1, float s2, float s3)
	{
		score[0] = s1;
		score[1] = s2;
		score[2] = s3;
		total = score[0] + score[1] + score[2];
		ave = total / (float) 3.0;
	}
	void SetAndAge(char *no, int age)
	{
		strncpy(this->stuno, no, 20);
		this->SetAge(age);
	}

	void ShowAll()
	{
		ShowInfo();
		cout << "学号:" << stuno << endl;
		cout << "三门成绩:" << score[0] << "\t" << score[1] << "\t" << score[2]
				<< endl;
		cout << "总成绩和平均分:" << total << "\t" << ave << endl;
	}
private:
	char stuno[20];
	float score[3], ave, total;
};

int main(void)
{
	CStudent one("LIMING", "001", 19);
	one.SetScore(90, 91, 92);
	one.ShowAll();
	one.SetNameAndSex("WANGFANG", 'M');
	one.SetAndAge("002", 18);
	one.ShowAll();

	return 0;
}
继承有public,private,protected。一定要区分清楚派生类的对象和派生类的成员函数对基类成员的访问不同
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值