实验目的:
(1)熟悉基类和派生类的转换;
(2)掌握继承和组合;
分析如下程序给出程序的运行结果:
#include<iostream>
using namespace std;
class A{
public:A(){
cout<<"A"<<endl;
}
};
class B{
public:B(){
cout<<"B"<<endl;
}
};
class C:public A,public B{
public:
C():a(),b(){};
private:
B b;
A a;
};
int main(){
C();
}
实 验 一
定义一个“点”类Dot,包含数据成员x,y(坐标点),在平面上两点连成一条直线,定义一个直线类Line,求直线的长度和直线中点坐标, 数据自拟。
(提示:直线类继承Dot类,同时以Dot类作为其子对象)
程序代码:
#include<iostream>
#include<math.h>
//#include<iomap>
using namespace std;
class Dot
{
public:
double x;
double y;
void get();
};
class Line:public Dot
{
private:
double l,x1,y2;
public:
void L(Dot d1,Dot d2);
void mid(Dot d1,Dot d2);
};
void Dot::get()
{
cout<<"输入纵坐标、横坐标:"<<endl;
cin>>x>>y;
}
void Line::L(Dot d1,Dot d2)
{
double s;
s=sqrt((d1.x-d2.x)*(d1.x-d2.x)+(d1.y-d2.y)*(d1.y-d2.y));
cout<<"长度是:"<<s<<endl;
}
void Line::mid(Dot d1,Dot d2)
{
double xm,ym;
xm=(d1.x+d2.x)/2;
ym=(d1.y+d2.y)/2;
cout<<"中点坐标是:("<<xm<<","<<ym<<")"<<endl;
}
int main()
{
Dot d1,d2;
d1.get();
d2.get();
Line l;
l.L(d1,d2);
l.mid(d1,d2);
return 0;
}
实 验 二
分别定义类如下:
(1) Birthday(生日类) 含有:year(年), month (月),日 (day) 等数据成员
(2) Staff(职工类)含有:num(工号),name(姓名),sex(性别) 等数据成员
(3) Teacher(教师类)含有:职工类和生日类的数据成员
要求:
(1)通过对Staff和Birthday使用继承和组合的方式设计Teacher;
(2)定义Teacher类对象teach,并给出所有数据的初值,数据自拟;
(3)修改teach的生日数据;
(4)输出teach的全部最新数据。
程序代码:
#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 Staff:public Teacher
{
public:
Staff(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 c)
{
num=n;
name=nam;
sex=c;
}
void Teacher::display()
{
cout<<"num:"<<num<<endl;
cout<<"name:"<<name<<endl;
cout<<"sex:"<<sex<<endl;
}
Staff::Staff(int n,string nam,char c,BirthDate day):Teacher(n,nam,c),birthday(day){}
void Staff::display()
{
Teacher::display();
birthday.display();
}
void Staff::setbirthday(int i,int m ,int n)
{
birthday.setbirthday(i,m,n);
}
int main()
{
int num;
string name;
char sex;
int year,month,day;
cin>>num>>name>>sex;
cin>>year>>month>>day;
Staff prof(num,name,sex,BirthDate(year,month,day));
cout<<"修改数据"<<ebdl;
cin>>year>>month>>day;
prof.setbirthday(year,month,day);
prof.display();
return 0;
}