第一题
这个题目其实就是简答的类的继承,需要注意一下的点有
- professor类的头文件中需要引用
teacher.h
和birthday.h
,在继承的时候最好显示显式表示是以pulic还是别的什么格式继承的teacher类 - 关于类的构造方法。这块记得如果写了带参数的构造方法,那一定要补上一个不带参数的构造方法,不然后面不过是组合还是继承都容易会报错
这个是我拿processOn画的一个类图,实现表示继承,虚线表示组合,箭头指向被引用/组合的对象
professor.h如下
#ifndef PROFESSOR_H
#define PROFESSOR_H
#include <iostream>
#include "teacher.h"
#include "birthday.h"
using namespace std;
class professor:public teacher
{
public :
birthday bir;
professor():bir(0,0,0){};//为什么这么写?不加是否会报错?原因?
void initialize();
void display();
};
#endif /* PROFESSOR_H */
professor.cpp如下
#include "professor.h"
using namespace std;
void professor::initialize()
{
cin >> num >> name >> sex
>> bir.year >> bir.month >> bir.day;
}
void professor::display()
{
printf("num:%d\nname:",num);
cout << name << endl;
cout << "sex:" << sex << endl;
cout << "birthday:" << bir.year << '/' << bir.month << '/' << bir.day;
}
第二题
这个主要是理清子类是如何调用父类的方法,这个老师也说过,不过也可以看看这个博客C++继承解析
最后展示下类图
为了便于展示,这里就不写cpp,直接在头文件展示了
building.h如下
#ifndef BUILDING_H
#define BUILDING_H
#include<iostream>
using namespace std;
class Building
{
protected:
int layerNumber;
int houseNum;
float areaSum;
public:
Building(int m,int n,float s)
{
layerNumber=m;
houseNum=n;
areaSum=s;
cout<<"base constructor called."<<endl;
}
virtual void print()
{
cout<<"this is a "<<layerNumber<<"-story building"<<endl;
cout<<"there are "<<houseNum<<" houses"<<endl;
cout<<"And total area is "<<areaSum<<endl;
}
};
#endif /* BUILDING_H */
house.h
#ifndef HOUSE_H
#define HOUSE_H
#include "building.h"
class House :public Building
{
public:
int bedroomNum;
int bathroomNum;
House(int a,int b,float c,int d,int e):Building(a,b,c)
{
bedroomNum=d;
bathroomNum=e;
cout<<"House constructor called."<<endl;
}
void print()
{
cout<<"this is a "<<layerNumber<<"-story building"<<endl;
cout<<"there are "<<houseNum<<" houses"<<endl;
cout<<"And total area is "<<areaSum<<endl;
cout<<"bedroomnum="<<bedroomNum<<endl;
cout<<"bathroomnum="<<bathroomNum<<endl;
}
};
#endif /* HOUSE_H */
office.h
#ifndef OFFICE_H
#define OFFICE_H
#include "building.h"
class Office: public Building
{
public:
int stuffNum;
int telNum;
Office(int a,int b,float c,int d,int e):Building(a,b,c)
{
stuffNum=d;
telNum=e;
cout<<"Office Constructor called."<<endl;
}
void print()
{
cout<<"this is a "<<layerNumber<<"-story building"<<endl;
cout<<"there are "<<houseNum<<" houses"<<endl;
cout<<"And total area is "<<areaSum<<endl;
cout<<"stuffnum="<<stuffNum<<endl;
cout<<"telnum="<< telNum<<endl;
}
};
#endif