C上机实验报告实验六

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

C上机实验报告实验六 Last revision date: 13 December 2020.

实验六

实验目的

1.掌握运算符重载的方法

2.学习使用虚函数实现动态多态性

实验要求

1.定义Point类,有坐标_x,_y两个成员变量;对Point类重载“++”(自增)、“――”(自减)运算符,实现对坐标值的改变。

2.定义一个车(vehiele)基类,有Run、Stop等成员函数,由此派生出自行车(bicycle)类、汽车(motorcar)类,从bicycle和motorcar派生出摩托车(motorcycle)类,它们都有Run、Stop等成员函数。观察虚函数的作用。

3.(选做)对实验4中的People类重载“==”运算符和“-”运算符,“==”运算符判断两个people类对象的id属性是否相等;“-”运算符实现People类对象的赋值操作。

实验内容及实验步骤

1.编写程序定义Point类,在类中定义整型的私有成员变量_x_y,定义成员函数Point&operator++();Pointoperator++(int);以实现对Point类重载

“++”(自增)运算符,定义成员函数Point&operator--();Pointoperator --(int);以实现对Point类重载“--”(自减)运算符,实现对坐标值的改变。程序名:1ab8_1.Cpp

#include

usingnamespacestd;

classPoint

{

public:

Point();

Point(intx,inty);

~Point(){}//Point类析构函数

Point&operator++();//公有成员函数

Pointoperator++(int);

Point&operator--();

Pointoperator--(int);

voidShow();

private:

int_x;//私有数据成员

int_y;

};

Point::Point(){//Point类构造函数

_x=0;_y=0;}

Point::Point(intx,inty)//Point类构造函数

{

_x=x;

_y=y;

}

Point&Point::operator++()//重载后置++运算符为Point类成员函数{

_x++;

_y++;

}

PointPoint::operator++(int)//重载前置++运算符为Point类成员函数{

Pointold=*this;

++(this->_x);

++(this->_y);

returnold;

}

Point&Point::operator--()//重载后置--运算符为Point类成员函数{

_x--;

_y--;

}

PointPoint::operator--(int)//重载前置--运算符为Point类成员函数{

Pointold=*this;

--(this->_x);

--(this->_y);

returnold;

}

voidPoint::Show()//输出Point的坐标值

{

cout<<_x<<","<<_y<<")"<

}

intmain()

{

Pointa(2,3);//定义一个Point类对象a

Pointb=a++;//定义Point类对象b并用a++初始化b

Pointc=++a;//定义Point类对象c并用++a初始化c

Pointd=--a;//定义Point类对象d并用--a初始化d

Pointe=a--;//定义Point类对象e并用a--初始化e

cout<<"Pointa(";

a.Show();//输出a的坐标

cout<<"Pointb(";

b.Show();//输出b的坐标

cout<<"Pointc(";

c.Show();//输出c的坐标

cout<<"Pointd(";

d.Show();//输出d的坐标

cout<<"Pointe(";

e.Show();//输出e的坐标

return0;

}

运行结果:

2编写程序定义一个车(vehicle)基类,有Run、Stop等成员函数,由此派生出自行车(bicycle)类、汽车(motorcar)类,从bicycle和motorcar派生出摩托车(motorcycle)类,它们都有Run、Stop等成员函数。在main()函数中定义vehicle、bicycle、motorcar、motorcycle的对象,调用其Run()、Stop()函数,观察其执行情况。再分别用vehicle类型的指针来调用这几个对象的成员函数,看看能否成功;把Run、Stop定义为虚函数,再试试看。

程序名:lab8_2.cpp

#include

usingnamespacestd;

classvehicle//基类vehicle

{

public:

vehicle(){}

~vehicle(){}

virtualvoidRun(){cout<<"Thevehicleisrunning!"<

virtualvoidStop(){cout<<"Thevehiclehasstopped!"<

};

classbicycle:virtualpublicvehicle//定义派生类bicycle,声明基类为派生类的虚基类

{

public:

voidRun(){cout<<"Thebicycleisrunning!"<

voidStop(){cout<<"Thebicyclehasstopped!"<

bicycle(){}

~bicycle(){}

};

classmotorcar:virtualpublicvehicle//定义派生类motorcar,声明基类为派生类的虚基类

{

public:

voidRun(){cout<<"Themotorcarisrunning!"<

voidStop(){cout<<"Themotorcarhasstopped!"<

motorcar(){}

相关文档
最新文档