#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。一定要区分清楚派生类的对象和派生类的成员函数对基类成员的访问不同
简单的继承模版
最新推荐文章于 2023-05-28 01:01:28 发布