天津理工大学c++实验三

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

实验三派生与继承

(2018-11-1)

一、实验名称:

派生与继承。

二、实验目的:

(1)理解继承的含义,掌握派生类的定义方法和实现;

(2)理解公有继承下基类成员对派生类成员和派生类对象的可见性,能正确地访问继承层次中的各种类成员;

(3)理解保护成员在继承中的作用,能够在适当的时候选择使用保护成员以便派生类成员可以访问基类的部分非公开的成员;

(4)理解虚函数在类的继承层次中的作用,虚函数的引入对程序运行时的影响,能够对使用虚函数的简单程序写出程序结果。

三、实验学时:4学时

四、练习项目

1.先定义“点”类Point,再由“点”类派生出“圆”类Circle。

#include

#define PI 3.14159

class Point // 定义“点”类

{

int x, y;

public:

Point(int a=0, int b=0)

{ x=a; y=b; }

void ShowPoint( )

{ cout<<"Point:("<

int Getx( )

{ return x; }

int Gety( )

{ return y; }

void Setxy(int a, int b)

{ x=a; y=b; }

};

class Circle: public Point// 定义“圆”类,公有继承{

int r;// “圆”的半径

public:

Circle(int x, int y, int ra) : Point(x, y)// B

{ r = ra; }

void Setr(int ra)

{ r = ra; }

double Area( ) //求圆的面积

{ return PI*r*r; }

void Move(int x_offset, int y_offset) //将圆心坐标平移{

int x1=Getx( ); //存取基类的私有成员

int y1=Gety( ); // D

x1 += x_offset; y1 += y_offset;

Setxy(x1, y1); // E }

void ShowCircle( )

{

ShowPoint( ); // F

cout<<" Radius: "<

cout<<"Area: "<

};

void main( )

{

Circle c(1, 1, 1);

c.ShowCircle( );

c.Move(1, 2);

c.ShowCircle( );

c.Setxy(4, 5); //重新置圆心坐标

c.Setr(2); //重新置半径值

c.ShowCircle( );

}

(1)记录程序的运行结果

(2)测试能否将move函数体改写为

x=x+x_offset;

y=y+y_offset;

2: 先定义“点”类Point和“半径”类Radius,再由Point类和Radius类多重派生出“圆”类Circle。

#include

#define PI 3.14159

class Point

{

protected://A

int x, y;

public:

Point(int a=0, int b=0){ x=a; y=b; }

void ShowPoint( )

{ cout<<"Point:("<

int Getx( ) { return x; }

int Gety( ) { return y; }

void Setxy(int a, int b){ x=a; y=b; }

};

class Radius

{

protected: //B

int r;

public:

Radius(int ra=0){ r = ra; }

void Setr(int ra){ r = ra; }

int Getr( ){ return r; }

};

class Circle : public Point, public Radius

{

public:

Circle(int x, int y, int ra) : Point(x, y), Radius(ra)//D { }

double Area( )

{ return PI*r*r; } //直接访问基类的保护成员

void Move(int x_offset, int y_offset)

{ x += x_offset; y += y_offset; }

void ShowCircle( )

{

ShowPoint( );

cout<<"Radius: "<

cout<<"Area: "<

}

};

void main( )

{

Circle c(1, 1, 1);

c.ShowCircle( );

c.Move(1, 2);

c.ShowCircle( );

c.Setxy(4, 5);

c.Setr(2);

c.ShowCircle( );

}

(1)记录程序的运行结果

(2)为什么可以直接使用x,y,

相关文档
最新文档