C++上机实验|继承与派生编程练习

1.实验目的

(1) 掌握派生与继承的概念与使用方法
(2) 运用继承机制对现有的类进行重用。
(3) 掌握继承中的构造函数与析构函数的调用顺序,
(4) 为派生类设计合适的构造函数初始化派生类。
(5) 深入理解继承与组合的区别。

2.实验内容

设计一个人员类 person 和一个日期类 date,由人员类派生出学生类 student 和教师类professor,学生类和教师类的数据成员 birthday 为日期类。

3. 参考代码

#include	
#include
using namespace std;
class date   //日期类
{
private:
   int year;
   int month;
   int day;
public:
   date()
   {
	  cout<<"Birthday:";
       cin>>year>>month>>day;
   }
   void display()
   {
	   cout<<year<<"-"<<month<<"-"<<day;
   }
};
class person   							//人员类
{
protected:
    char *name;
public:
    person();
};
person::person()
{
	  char namestr[50];
	  cout<<"Name:";
	  cin>>namestr;
	  name=new char[strlen(namestr)+1];
	  strcpy(name,namestr);
}
class student:public person   			//学生类
{
private:
	int ID;
	int score;
	date birthday;
public:
	student()
	{
	  cout<<"Student ID:"<<endl;
	  cin>>ID;
	  cout<<"Student score:"<<endl;
	  cin>>score;
	}
	void display()
	{  
		cout<<"The basic information: "<<endl;
		cout<<ID<<"\t"<<name<<"\t"<<score<<"\t";
		birthday.display();
		cout<<endl;
	}
};
class professor:public person   //教师类
{
private:
	int NO;
	char major[10];
	date birthday;
public:
	professor()
	{
		cout<<"Teacher ID:"<<endl;
		cin>>NO;
		cout<<"school teaching major:"<<endl;
		cin>>major;
	}
	void display()
	{
	    cout<<"The basic information:"<<endl;
	    cout<<"\t"<<NO<<"\t"<<name<<"\t"<<major<<"\t";
	    birthday.display();
	    cout<<endl;
	}
};
int main()
{
   student stu;
   stu.display();
   professor prof;
   prof.display();
   system("pause");
   return 0;
}

C++上机实验|继承与派生编程练习_第1张图片

程序解释:
(1)student stu;
首先初始化student 的基类person;然后初始化成员类date;因此要求输入姓名、出生日期;
(2) stu.display();
(3)professor prof;语句执行过程同student stu;,但实际执行过程中存在问题,考虑二义性或命令行环境的差异,暂不深究。

你可能感兴趣的:(C++语言程序设计教程,c++,开发语言)