C++习题 继承与组合

C++习题 继承与组合

时间: 1ms        内存:128M

描述:

已知类如下:
(1) BirthDate(生日类) 含有:year,month,day 等数据成员
(2) Teacher(教师类)含有:num,name,sex 等数据成员
(3) Professor(教授类)含有:教师类和生日类的数据成员
要求:
(1)通过对Teacher和BirthDate使用继承和组合的方式设计Professor
(2)定义Professor类对象prof,并给出所有数据的初值
(3)修改prof的生日数据
(4)输出prof的全部最新数据

输入:

 num,name,sex,year,month,day 和修改后的year,month,day

输出:

 num,name,sex,year,month,day 

示例输入:

2001 Huang m
1970 1 1
1994 5 26

示例输出:

num:2001
name:Huang
sex:m
birthday:1994/5/26

提示:

参考答案(内存最优[1092]):

#include <stdio.h>
int  main()
{
    int num;
    char name[30],sex;
    int y,m,d;
    scanf("%d %s %c %*d%*d%*d%d %d%d",&num,name,&sex,&y,&m,&d);
    printf("num:%d\nname:%s\nsex:%c\nbirthday:%d/%d/%d\n",num,name,sex,y,m,d);
    return 0;
}

参考答案(时间最优[0]):


#include <iostream>
#include <string>
using namespace std;
class BirthDate {
public:
    BirthDate(int,int,int);
    void display();
    void setbirthday(int,int,int);
private:
    int year;
    int month;
    int day;
};
class Teacher
{
public:
    Teacher(int,string,char);
    void display();
private:
    int num;
    string name;
    char sex;
};
class Professor:public Teacher
{
public:
    Professor(int,string,char,BirthDate);
    void display();
    void setbirthday(int,int,int);
private:
    BirthDate birthday;
};
BirthDate::BirthDate(int y,int m,int d):year(y),month(m),day(d){}
void BirthDate::display()
{cout<<"birthday:"<<year<<"/"<<month<<"/"<<day<<endl;}
void BirthDate::setbirthday(int y,int m,int d)
{
   year=y;
   month=m;
   day=d;


}
Teacher::Teacher(int n,string nam,char s):num(n),name(nam),sex(s){}
void Teacher::display()
{cout<<"num:"<<num<<endl;

cout<<"name:"<<name<<endl;
cout<<"sex:"<<sex<<endl;

}


int y,m,d;
Professor::Professor(int n,string nam,char s,BirthDate):Teacher(n,nam,s),birthday(y,m,d){}
void Professor::display()
{


Teacher::display();

birthday.display();
}


void Professor::setbirthday(int y,int m,int d)
{birthday.setbirthday(y,m,d);}

int main()
{
    int num;
    string name;
    char sex;
    int year,month,day;
    cin>>num>>name>>sex;
    cin>>year>>month>>day;
    Professor prof(num,name,sex,BirthDate(year,month,day));
    cin>>year>>month>>day;
    prof.setbirthday(year,month,day);
    prof.display();
    return 0;
}

题目和答案均来自于互联网,仅供参考,如有问题请联系管理员修改或删除。

点赞

发表评论

电子邮件地址不会被公开。必填项已用 * 标注