问题 J: oop实习-10. 虚函数

在这里插入图片描述

#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;

class P{
	protected:
		string name;
	public:
		P(string s) { this->name = s;}
		virtual void print()
		{
			cout<<"Person "<<name<<endl;
		}
};

class S:public P{
    protected:
    	int num;
    public:
    	S(string s,int i) :P(s) 
    	{
    		this->num = i;
		}
    	void print()
    	{
    		cout<<"Student "<<name<<" "<<num<<endl;
		}
};

class T:public P{
	protected:
    	int year;
    public:
    	T(string s,int i):P(s)
    	{
    		this->year = i;
		}
    	void print()
    	{
    		cout<<"Teacher"<<" "<<name<<" "<<year<<endl;
		}
};

class G:public S{
	protected:
    	string r;
    public:
    	G(string s,int i,string a):S(s,i)
    	{
    		this->r = a;
		}
    	void print()
    	{
    		cout<<"Graduate "<<name<<" "<<num<<" "<<r<<endl;
		}
};

void f(P *r)
{
	r->print() ;
}
int main()
{
	int i,n,num;
	cin>>n;
	P *p[n];
	string s,a,b,c;
	for(i = 0;i < n;i++)
	{
		cin>>s;
		if(s=="Person")
		{
			cin>>a;
			p[i] = new P(a);
		}
		else if(s=="Student")
		{
			cin>>a>>num;
			p[i] = new S(a,num);
		}
		else if(s=="Graduate")
		{
			cin>>a>>num>>b;
			p[i] = new G(a,num,b);
		}
		else if(s=="Teacher")
		{
			cin>>a>>num;
			p[i] = new T(a,num);
		}
	}
		char s1[20];
		cin>>s1;
	while(strcmp(s1,"exit"))
	{
		int m=atoi(s1);
		f(p[m]);
		cin>>s1;
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值