⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ex_publicderived.cpp

📁 Visual C++应用教程-源代码 本书在复习C++基础知识后
💻 CPP
字号:
// [例Ex_PublicDerived] 派生类的公有继承示例
#include <iostream.h>
#include <string.h>

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);
		this->age = 20;
	}
public:
	void SetScore( float s1, float s2, float s3 )
	{
		score[0] = s1;		score[1] = s2;			score[2] = s3;
		total = s1 + s2 + s3;
		ave = total / (float)3.0;
	}
	void SetNoAndAge(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()
{
	CStudent one("LiMing", "21050101", 19 );
	one.SetScore( 90, 80, 84);
	one.ShowAll();
	one.SetNameAndSex("WangFang", 'W');
	one.SetNoAndAge("21050102", 18 );
	one.ShowAll();
		CStudent two("WangFang", 19, 'M');

	return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -