C上机实验报告实验六

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

C上机实验报告实验六公司内部编号:(GOOD-TMMT-MMUT-UUPTY-UUYY-DTTI-

实验六实验目的

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++();Point operator++(int);以实现对

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

#include

using namespace std;

class Point

{

public:

Point();

Point(int x,int y);

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

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

Point operator++(int);

Point&operator--();

Point operator--(int);

void Show();

private:

int _x; //私有数据成员

int _y;

};

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

_x=0;_y=0;}

Point::Point(int x,int y) //Point类构造函数

{

_x=x;

_y=y;

}

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

{

_x++;

_y++;

}

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

{

Point old=*this;

++(this->_x);

++(this->_y);

return old;

}

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

{

_x--;

_y--;

}

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

{

Point old=*this;

--(this->_x);

--(this->_y);

return old;

}

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

{

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

}

int main()

{

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

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

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

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

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

cout<<"Point a(";

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

cout<<"Point b(";

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

cout<<"Point c(";

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

cout<<"Point d(";

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

cout<<"Point e(";

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

return 0;

}

运行结果:

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

using namespace std;

class vehicle

//基类vehicle

{

public:

vehicle(){}

~vehicle(){}

virtual void Run(){cout<<"The vehicle is running!"<

virtual void Stop(){cout<<"The vehicle has

stopped!"<

相关文档
最新文档