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

来源:互联网 发布:deepin linux 安装软件 编辑:程序博客网 时间:2024/06/07 04:29

定义了一个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
原创粉丝点击