输出教师和学生的信息

版权声明:私藏源代码是违反人性的罪恶行为!博客转载无需告知,学无止境。 https://blog.csdn.net/qq_41822235/article/details/83052462

基类: 

#include<iostream>
#include<string>
using namespace std;

/*实现一个函数打印学生、老师信息*/
class person
{
public:
	person(string name, string sex, int age)
		:_name(name), _sex(sex), _age(age)
	{ }
	virtual void display() = 0;		//纯虚函数
protected:
	string _name;
	string _sex;
	int _age;
};

 教师类(派生类一):

class teacher : public person
{
public:
	teacher(string name, string sex, int age, string rank)
		:person(name, sex, age),_rank(rank)
	{ }
	void display_part();    //使用该函数取代输出教师属性的函数
private:
	virtual void display();        //放在私有是故意为之,为了实现对教师隐私的保护
	string _rank;
};

void teacher::display()
{
	cout << "name: " << _name;
	cout << " sex: " << _sex;
	cout << " age" << _age;
	cout << " rank: " << _rank << endl;
}

void teacher::display_part()	//对教师的年龄属性进行隐藏
{
	cout << "name: " << _name;
	cout << " sex: " << _sex;
	cout << " rank: " << _rank;
}

学生类(派生类二): 

class student : public person
{
public:
	student(string name, string sex, int age, double score)
		:person(name, sex, age), _score(score)
	{ }
	virtual void display();
private:
	double _score;
};

void student::display()
{
	cout << "name: " << _name;
	cout << " sex: " << _sex;
	cout << " age: " << _age;
	cout << " score: " << _score << endl;
}

全局函数:

void show(person *ptr)
{
	teacher *ptea = dynamic_cast<teacher *>(ptr);
	if (NULL == ptea)
	{
		ptr->display();
	}
	else
	{
		ptea->display_part();
	}
}

测试用例:

int main()
{
	teacher tea1("王", "男", 30, "助教");
	student st1("马云", "男", 50, 100);
	show(&st1);
	show(&tea1);
	cout << endl;
	return 0;
}

运行结果:

图1 VS2017运行结果

如图1 所示,对于教师而言,实现了对年龄属性的隐藏。 

猜你喜欢

转载自blog.csdn.net/qq_41822235/article/details/83052462