实验四 继承、派生与多态.doc
文本预览下载声明
西华大学计算机系上机实践报告
课程:级::名称: 上机实践日期:09-11-19 上机实践编号:组:
一、二、内容与上机内容print( )公有成员函数,另定义研究生类Postgraduate,它以公有继承方式派生于类Graduate,新增加“研究方向、导师名”两个私有数据成员,并定义带参数的构造函数,拷贝构造函数、析构函数和输出研究生数据的print( )公有成员函数,另外,要求学号自动增加,且Graduate和Postgraduate的学号起始值不同。在主函数中定义派生类对象进行测试。(字符串用char*表示)
思路:在基类和派生类中各定义一个静态成员count记数,在构造函数中逐加实现学号逐加,但在派生类构造函数中要对基类的记数逐减,防止基类记数的跳跃。
2. 请编写一个抽象类Shape,在此基础上派生出类Rectangle和Circle,二者都有计算对象面积的函数GetArea()、计算对象周长的函数GetPerim()。在主函数中定义抽象类的对象指针数组实现对不同派生类对象及其成员函数的测试。
思路:矩形和圆没有相同的成员、计算公式的函数,在shape中定义纯虚构函数;
在矩形和圆的派生类中定义各自的成员和公式函数。
3.请完成Complex类的定义,使得下面的主函数能正常运行。
int main( )
{
Complex c1(1,2);
coutc1=c1; //operator(cout,c1);
Complex c2(2); // default argument is i=0
coutc2=c2endl;
Complex c3(c1); //invoke the copy constructor
coutc3=c3;
c1=c1+c2+c3; // c1=(c1.operator+(c2)).operator+(c3);
coutc1=c1+c2+c3=c1;
c2=-c3; // c2=c3.operator-();
coutc2=-c3=c2;
c3=c2-c1; // c3=c2.operator-(c1);
coutc3=c2-c1= c3;
Complex r2=2+c2; // calls operator+ (2, c2)
coutr2=2+c2=r2;
Complex c4;
cinc4;
coutc4=c4;
coutthe module of c4 is: c4.GetMagnitude()endl;//计算复数的模
return 0;
}
思路:在类中对“+、—、=、、”运算符重载。
三、用环境
Windowns XP
C++环境:Visual C++ 6.0
四
1
. int Graduate::count
Graduate::Graduate(char *str1,char *str2)
{
name=new char[strlen(str2)+1];
shool=new char[strlen(str1)+1];
strcpy(name,str2);
strcpy(shool,str1);
number=count++;
}
Graduate::Graduate(Graduate const gra)
{
name=new char[strlen(gra.name)+1];
shool=new char[strlen(gra.shool)+1];
strcpy(name,gra.name);
strcpy(shool,gra.shool);
number=count++;
}
Graduate Graduate::operator=(Graduate G)
{
if(this==G)
return *this;
else
{
delete []name;
delete[]shool;
name=new char[strlen(G.name)+1];
shool=new char[strlen(G.shool)+1];
strcpy(name,G.name);
strcpy(shool,G.shool);
number=G.number;
}
return *this;
}
void Graduate::print()
{
coutnumbersetw(8)namesetw(20)shoolendl;
}
Graduate::~Graduate()
{
delete []name;
delete []shool;
}
int Postgraduate::pcount
Postgraduate::Post
显示全部