学习C++(十)

继承的案例

#include <iostream>
using namespace std;
/*
定义一个人员类Person,包含数据成员:姓名、ID。
在此基础上派生出学生类Student(增加成绩属性)和老师类Teacher(增加教龄)。
主函数测试实现对学生和老师信息的输入输出。
*/
class Person{
   
private:
	string name;
	int id;
public:
    //构造函数
	Person(const string& name, int id);
    
    //get set
	const string& getName() const {
    return this->name; }
	int getId() const {
    return this->id; }

	void setName(const string& name) {
    this->name = name; }
	void setId(int id) {
    this->id = id; }

	//虚方法
	virtual void display() const{
   }//输出
	virtual void input() {
   }//输入
};

class Student : public Person{
   
private:
	int score;
public:
	Student(const string& name, int id, int score);

	void display() const;
	void input();
};

class Teacher : public Person{
   
private:
	int teacherYear;
public:
	Teacher(const string& name, int id, int teacherYear);

	void display() const;
	void input();
};

Person::Person(const string& name, int id)
	:name(name),
	id(id)
{
   

}

Student::Student(const string& name, int id, int score)
	:Person(name, id),
	score(score)
{
   

}

Teacher::Teacher(const string& name, int id, int teacherYear)
	:Person(name, id),
	teacherYear(teacherYear)
{
   

}

void Student::display() const
{
   
	cout << "这是学生:";
	cout << this->getId() << "\t" << this->getName()
		<< "\t" << this->score << endl;
}

void Student::input()
{
   
	string name;
	int id = 0;
	cin >> name >> id >>this->score;
	this->setName(name);
	this->setId(id);
}

void Teacher::display() const
{
   
	cout << "这是老师:";
	cout << this->getId() << "\t" << this->getName()
		<< "\t" << this->teacherYear << endl;
}

void Teacher::input()
{
   
	string name;
	int id = 0;
	cin >> name >> id >> teacherYear;
	this->setName(name);
	this->setId(id);
}

int main()
{
   
	Student tom(&
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值