以下将以一个程序为例,带大家认识一下继承的好处。
代码样例:
#include <iostream>
using namespace std;
class Person
{
public:
void IntroduceMe() //自我介绍
{
string gender= (sex=='M'?"Male":"Female");
cout<<"My Name is "<<name<<", " <<gender<<", "<<age<<" years old."<<endl;
}
void Eat() //吃饭
{
cout<<"I'm hungry! I'd like something to eat! "<<endl;
}
void Rest() // 睡觉
{
cout<<"I'm tired. I need to rest."<<endl;
}
//Constructor and Destructor 构造函数和析构函数
Person(string Name,char Sex,int Age)
{
name=Name;
sex=Sex;
age=Age;
//cout<<"Person("<<name<<"): is constructed!"<<endl;
}
~Person()
{
// cout<<"Person("<<name<<"): is destructed!"<<endl;
}
protected:
string name;
char sex;
int age;//这些信息后文Lisi也要用到;
int hunger,vitality; //饥饿值和精力值,可以定义具体值的含义
};
class Student:public Person //公共继承
{
public:
void IntroduceMe()
{
cout<<"我的学号是"<<stuid<<", 我是一名学生!"<<endl;
Person::IntroduceMe(); //调用基类的同名函数
}
void Study()
{
cout<<"我在上课!"<<endl;
}
void Examination()
{
cout<<"我在考试!"<<endl;
}
//构造函数和析构函数
Student(string Stuid,string Name,char Sex,int Age):Person(Name,Sex,Age)
{
stuid=Stuid;//在Person的基础上加上一个信息stuid;不用再次重复已有的信息;
}
~Student()
{
}
protected:
string stuid;
//string major;//专业
};
int main()
{
//cout << "Hello world!" << endl;
Person p1("zhangsan",'M',19);
//p1.hunger=20;
p1.IntroduceMe();
p1.Eat();
p1.Rest();
cout<<"-------------------------------------------------"<<endl;
Student s1("0001","Lisi",'F',18);
s1.IntroduceMe();
s1.Eat();
s1.Examination();
//当把这个学生 对象 看做一个 人 的对象时
cout<<"-------------------------------------------------"<<endl;
Person * p2= &s1;
p2->IntroduceMe();//指针的用处是不是也很方便-~-
return 0;
}
运行结果: