继承与派生、运算符的重载、虚函数的应用
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;
}
代码:
#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/C++日常学习总结(第三篇)不能重载的运算符和不同基类继承产生的二义性
- 10-2 继承与派生应用(CPerson类)
- mfc 序列化类(串行化类)的继承和虚函数应用
- 继承,虚函数应用,对象向量
- 继承和派生的应用2
- c++ 继承 虚函数与多态性 重载 覆盖 隐藏
- c++ 继承 虚函数与多态性 重载 覆盖 隐藏
- 虚函数,重载,继承叠加产生的问题
- Scala学习整理[第十章 继承重载应用]<Programming In Scala>
- 继承与派生,多继承,函数重载,构造函数调用顺序 静态多态和动态多态
- C++继承-重载-多态-虚函数
- 飛飛(五十六)班长与学生的信息(继承和派生的应用)
- c++基础10:继承和派生 虚函数的作用 多态性概念 纯虚函数和抽象类的概念
- 继承和虚函数在NS2中的应用(更好地理解累的继承)
- 关于重载,覆盖/隐藏,虚函数,纯虚函数,多重继承
- 继承与派生,多继承,函数重载,构造函数调用顺序
- C++ 虚函数;重载与覆盖;虚继承
- c++(一) 类 对象 重载 继承 多态 构造函数 虚函数 覆盖 纯虚函数等
- C++学习笔记13:类继承和派生、虚函数
- 继承与派生的应用3