您的位置:首页 > 编程语言 > C语言/C++

C++编程实例-多态(二)

2016-01-26 00:00 537 查看
实验14 多态(二)
【实验目的】
通过本实验,掌握类的纯虚函数的概念。
【实验要求】
熟练掌握纯虚函数的定义及使用方法。
【实验内容】
简单模拟输入学生的姓名及考试成绩,计算并显示学生成绩的学分值。
类S和类GS公有继承类Base。类Base的input()、output()函数、 get() 函数、score () 函数为纯虚函数。
#include<cstdio>
#include<iostream>
using namespace std;
const int N=4;
const int M=5;
class Base{ //共有基类
public:
virtual void input()=0;
virtual void output()=0;
virtual char *get()=0;
virtual void score()=0;
void space(char *p); //去掉字符串的空格
int check(int i); //成绩合理性检验
};
int Base::check(int i){
int x=-1;
while(x<=0||x>100){
cout<<"第"<<i+1<<"个成绩=";
cin>>x;
if(x>=0&&x<=100) break;
}
return x;
}
void Base::space(char *p){
char *q=p;
while(*p!='/0'){
if(*p!=' ')*q++=*p;
p++;
}
*q='/0';
}
class S:public Base{ //模拟大学生类定义
private:
char *k;
int s
,sum;
char x;
public:
S(){ k=new char[100]; sum=0; }
~S(){ delete []k; }
void input(); //输入学生姓名
void output(); //输出学生的学分值
char *get(){ return k; }
void score(); //成绩处理
};
void S::input(){cout<<"输入一个(S)学生的姓名:"; gets(k); }
void S::output(){ cout<<"(S)学生"<<k<<"的学分值 x="<<x<<endl; }
void S::score(){
cout<<"输入(S)学生"<<k<<"的成绩"<<endl;
for(int i=0;i<N;i++){
s[i]=check(i); sum+=s[i];
}
getchar();
if((float)sum/N>=70) x='1'; //平均分大于等于70分时学分值为1
else x='0';
}
class GS:public Base{ //模拟研究学生类定义
private:
char *k;
int s[M],sum;
char x;
public:
GS(){ k=new char[100]; sum=0; }
~GS(){ delete []k; }
void input(); //输入学生姓名
void output(); //输出学生的学分值
char *get(){ return k; }
void score(); //成绩处理
};
void GS::input(){ cout<<"输入一个(GS)学生的姓名:"; gets(k); }
void GS::output(){ cout<<"(GS)学生"<<k<<"的学分值 x="<<x<<endl; }
void GS::score(){
cout<<"输入(GS)学生"<<k<<"的成绩"<<endl;
for(int i=0;i<M;i++){
s[i]=check(i); sum+=s[i];
}
getchar();
if((float)sum/M>=75) x='1'; //平均分大于等于75分时学分值为1
else x='0';
}
void fun(Base &a){
a.input(); a.space(a.get()); a.score(); a.output();
}
int main(){
S a; fun(a);
GS b; fun(b);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: