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

定义了一个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;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值