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

继承与派生、运算符的重载、虚函数的应用

2017-12-18 11:12 253 查看
定义了一个person类,派生出一个student类,通过person的一个指针来调用student类中定义成虚函数的show函数,重载了运算符'>',比较两个学生的成绩,先比较总分,总分相同比较数学,重载流插入运算符,用来输出成绩较高的同学的各科成绩;

代码:

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

class person{
private:
string name;
int age;
char sex;
public:
void set_info(){
cin>>name>>age>>sex;
}
virtual void show(){
cout<<"name:"<<name<<" "<<"age:"<<age<<endl;
}
};
class student:public person{
private:
string major;
int id;
int math, english, computer;
int sum;
public:
void set_info(){
person::set_info();
cin>>major>>id>>math>>english>>computer;
}
int getsum(){
sum = math + english + computer;
return sum;
}
void show(){
person::show();
cout<<"major:"<<major<<" "<<"id:"<<id<<endl;
}
bool operator>(student &stu){
if(this->getsum() > stu.getsum()){
return true;
}
else if(this->sum == stu.getsum()){
if(this->math > stu.math){
return true;
}
}
else
return false;
}
friend ostream &operator<<(ostream &out, const student &stu){
out<<"math:"<<stu.math<<endl;
out<<"english:"<<stu.english<<endl;
out<<"computer:"<<stu.computer<<endl;
return out;
}
};
int main()
{
person *st;
student s, t;
s.set_info();
t.set_info();
st = &s;
st->show();
st = &t;
st->show();
cout<<"成绩高的同学的成绩是:"<<endl;
if(s > t)
cout<<s;
else
cout<<t;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++