c++习题继承与组合

  • Post author:
  • Post category:其他




将本章5.8节中的程序片段加以补充完善,成为一个完整的程序。在程序中使用继承和组合。在定义Professor类对象Prof1时给出所有数据的初值,然后修改prof1的生日数据,最后输出prof1的全部最新数据。

class Teacher 
{
	public:
	...
	private:
		int num;
		string name;
		char sex;
};

class Birthday
{
	public:
	...
	private:
		int year;
		int month;
		int day;
};

class Professor:public:Teacher
{
	public:
	...
	private:
		Birthday birth;
};



输入

先输入原始数据

num

name

sex

birthday year

birthday month

birthday date

area

然后输入修改的新

birthday year

birthday month

birthday date



输出

分别输出

original data:



new data:

格式参考样例



样例输入

3012

Zhang

f

1949

10

1

125.4

1950

6

1



样例输出

original data:

num:3012

name:Zhang

sex:f

birthday:10/1/1949

area:125.4

new data:

num:3012

name:Zhang

sex:f

birthday:6/1/1950

area:125.4



代码

#include<iostream>
#include<string>
using namespace std;
class Teacher
{
 public:
  Teacher(int n,string nam,string s){num=n;name=nam;sex=s;
  }
  void display(){
   cout<<"num:"<<num<<endl;
   cout<<"name:"<<name<<endl;
   cout<<"sex:"<<sex<<endl;
  }
  protected:
  int num;
  string name;
  string sex;
};
class Birthday
{
 protected:
  int year;
  int month;
  int day;
 public:
  Birthday(int y,int m,int d){year=y;month=m;day=d;
  } 
  void show(){
   cout<<"birthday:"<<month<<"/"<<day<<"/"<<year<<endl;
  }
  void show1(int y,int m,int d){
   year=y;
   month=m;
   day=d;
  }
};
class Professor:public Teacher
{
 public:
  Birthday birth;
  float area;
  Professor(int n,string nam,string s,int y,int m,int d,float a):Teacher(n,nam,s),birth(y,m,d){area=a;
  }
  void fun(){
   Teacher::display();
   birth.show();
   cout<<"area:"<<area<<endl; 
  } 
  void change(int y,int m,int d){
   Teacher::display();
   birth.show1(y,m,d);
   birth.show();
   cout<<"area:"<<area<<endl;
  }
};
int main()
{
 int a,y,m,d,y1,m1,d1;string b,c;
 cin>>m1>>d1>>y1;
 float ar;
 cin>>a>>b>>c>>y>>m>>d>>ar;
 Professor p1(a,b,c,y,m,d,ar);
 cout<<"original date:"<<endl;
 p1.fun();
 cout<<"new date:"<<endl;
 p1.change(m1,d1,y1);
 return 0;  
}



版权声明:本文为dlin_666原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。