继承与多态 用法
#include <iostream>
#include <string>
using namespace std;
class Person
{
public:
Person(string name, string sex, int age)
:_name(name)
,_sex(sex)
,_age(age)
{}
virtual void SelfIntroduce()
{
cout << "个人信息如下:";
cout << _name << " " << _sex << " " << _age << endl;
}
virtual void GetAdmissionFee()
{
cout << "票价为100元" << endl;
}
virtual void IsHappy()
{
cout << "我很幸福!" << endl;
}
protected:
string _name;
string _sex;
int _age;
};
class Student : public Person
{
public:
Student(string name, string sex, int age, int stuid, string goal)
:Person(name, sex, age)
,_stuid(stuid)
,_goal(goal)
{}
~Student()
{
_stuid = 0;
}
Student(const Student& other)
:Person(other)
,_stuid(other._stuid)
,_goal(other._goal)
{}
Student& operator=(const Student& other)
{
if (&other != this)
{
Person::operator=(other);
_stuid = other._stuid;
_goal = other._goal;
}
return *this;
}
virtual void SelfIntroduce() override
{
cout << "个人信息如下:";
cout << _name << " " << _sex << " " << _age << " " << _stuid << " " << _goal << endl;
}
void GetAdmissionFee()
{
cout << "票价为50元" << endl;
}
virtual void IsHappy()
{
cout << "我不幸福!" << endl;
}
protected:
int _stuid;
string _goal;
};
class Teather : public Person
{
public:
Teather(string name, string sex, int age, int jobid, bool ismarry)
:Person(name, sex, age)
, _jobid(jobid)
, _ismarry(ismarry)
{}
~Teather()
{
_jobid = 0;
}
Teather(const Teather& other)
:Person(other)
, _jobid(other._jobid)
, _ismarry(other._ismarry)
{}
Teather& operator=(const Teather& other)
{
if (&other != this)
{
Person::operator=(other);
_jobid = other._jobid;
_ismarry = other._ismarry;
}
return *this;
}
virtual void SelfIntroduce() override
{
cout << "个人信息如下:";
cout << _name << " " << _sex << " " << _age << " " << _jobid << " " << _ismarry << endl;
}
void GetAdmissionFee()
{
cout << "票价为110元" << endl;
}
virtual void IsHappy()
{
cout << "我不幸福!" << endl;
}
protected:
int _jobid;
bool _ismarry;
};
void CheckAdmissionFee(Person* person)
{
person->GetAdmissionFee();
}
void InformationDisplay(Person& person)
{
person.SelfIntroduce();
}
void Asking(Person* person)
{
person->IsHappy();
}
int main()
{
Person person1("张三", "男", 20);
person1.SelfIntroduce();
person1.GetAdmissionFee();
cout << endl;
Student person2("张三的弟弟", "男", 15, 1254, "好好学习技能");
person2.SelfIntroduce();
person2.GetAdmissionFee();
cout << endl;
Teather person3("张三的妈妈", "女", 40, 907, true);
person3.SelfIntroduce();
person3.GetAdmissionFee();
cout << endl;
CheckAdmissionFee(&person1);
CheckAdmissionFee(&person2);
CheckAdmissionFee(&person3);
cout << endl;
InformationDisplay(person1);
InformationDisplay(person2);
InformationDisplay(person3);
cout << endl;
Asking(&person1);
Asking(&person2);
Asking(&person3);
return 0;
}