people为基类,student和graduate为子类,重载“==”运算符

时间:2023-01-19 17:20:34

 //people为基类,student和graduate为子类,重载“==”运算符

//输入2个学生的信息:姓名、编号、身份证号、班级、专业

//输入1个研究生的信息:姓名、编号、身份证号、班级、专业、导师

//重载“==”,当两个学生的编号相同时,调用重载运算符,输出错误信息

源代码如下:

#include <iostream>
#include <string>
using namespace std;
//定义基类
class People

{

public:
//成员变量:姓名,编号,身份证号
  string name;
  string number;
  string id_number;

public:
  People() {} //无参数的构造函数
  People(string name1,string number1,string id_number1){
  name = name1;
  number = number1;
  id_number = id_number1;
}
//声明input,,output,类外定义
void input();
void output();
};
//定义基类的成员函数input()
void People:: input()

{
  //输入姓名,编号,身份证号
  cin >> name;
  cin >> number;
  cin >> id_number;
}
//定义基类的成员函数output()
void People:: output()

{
  //输出姓名,编号,身份证号
  cout << " name : " << name;
  cout << " number : " << number;
  cout << " id_number : " << id_number;
}

//子类student
class Student:public People

{
  //成员变量班级,专业
public:
  string Class;
  string major;
public:
  Student(){}
  Student(string name1,string number1,string id_number1,string Class1,string major1):People(name1,number1,id_number1){
  Class = Class1;
  major = major1;
}
void input();

void output();
bool operator ==(const Student &);

};
//子类的成员函数中,调用基类的成员函数input()
void Student::input()

{
  People::input();
  //输入班级专业
  cin>>Class>>major;
}
void Student::output()

{
  People::output();
  //输出班级专业
  cout << " Class : "<< Class;
  cout << " major : "<< major<<endl;

}
//运算符“==”重载
bool Student::operator ==(const Student &s)

{

  if(number ==s.number)

  {
    cout<<"两个学生编号相同,不合法!";
    exit(1);
  }

  else

  {
    return 1;
  }
}

//子类Graduate(研究生)
class Graduate:public Student

{
public:
  string daoshi;
public:
  Graduate(){}
  Graduate(string name1,string number1,string id_number1,string Class1,string major1,string daoshi1):Student(name1,number1,id_number1,Class1,major1)
  {
    daoshi = daoshi1;
  }
  void input();
  void output();
};

void Graduate::input()

{
  Student::input();
  cin >>daoshi;
}
void Graduate::output()

{
  Student::output();
  cout<<" daoshi : "<<daoshi<<endl;
}

int main()
{
  Student s1;
  Student s2;
  Graduate g;
  cout<<" please input the student info : "<<endl;
  s1.input();
  cout<<" please input the student info : "<<endl;
  s2.input();
  s1==s2; //调用“==”重载,判断两个学生的编号是否相同
  cout<<" please input the graduate info: "<<endl;
  g.input();
  cout<<" please show the students info:"<<endl;
  s1.output();
  s2.output();
  cout<<" show the graduate info: "<<endl;
  g.output();
  return 1;
}

 

运行结果: 

people为基类,student和graduate为子类,重载“==”运算符