C++上机实验报告 实验六 下载本文

内容发布更新时间 : 2024/9/20 11:40:33星期一 下面是文章的全部内容请认真阅读。

实验六多态性

1. 实验目的

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

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

2. 实验要求

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

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

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

3. 实验内容及实验步骤

1.编写程序定义Point类,在类中定义整型的私有成员变量_x_y,定义成员函数Point& operator++();Point operator++(int);以实现对Point类重载“++”(自增)运算符,定义成员函数Point&operator--();Point operator--(int);以实现对Point类重载“--”(自减)运算符,实现对坐标值的改变。程序名:1ab8_1.cpp。

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

4. 思考题

1. 如何将一个运算符重载为类的成员函数? 函数类型 operator 运算符(形参表) { 函数体; }

2. 如何将一个运算符重载为类的友元函数? friend函数类型operator 运算符(形参表) {

函数体; }

3.如何实现运行时刻的多态?

在基类的成员函数前加上virtual,就可以在它的派生类中声明相同名字和类型的成员函数,在运行过程中,系统会自动判断并调用相应类中的成员函数,从而在调用过程中实现多态。

5. 源程序 1. lab8_1.cpp #include

using namespace std; class Point {

private: int _x; int _y; public:

//构造.析构函数 Point(){}

Point(int,int); ~Point(){} //++.--重载

Point& operator ++(); Point operator ++(int); Point& operator --(); Point operator --(int); //输出点坐标 voidshowPoint(); };

Point::Point(intx,int y) {

_x=x; _y=y; }

Point& Point::operator ++() {

_x++; _y++; return *this; }

Point Point::operator ++(int) {

Point p=*this; ++(*this); return p; }

Point& Point::operator --() {

_x--; _y--; return *this; }

Point Point::operator --(int) {

Point p=*this; --(*this); return p; }

void Point::showPoint() {

cout<<\}

int main() {

Point apoint(3,5); apoint.showPoint();

(apoint++).showPoint();//测试后置++ apoint.showPoint();

(++apoint).showPoint();//测试前置++ apoint.showPoint();

(apoint--).showPoint();//测试后置-- apoint.showPoint();

(--apoint).showPoint();//测试前置-- apoint.showPoint();

return 0; }

2. lab8_2.cpp #include using namespace std; class Vehicle {

public:

//基类的成员函数为虚函数

virtual void run(){cout<<\virtual void stop(){cout<<\};

class Bicycle: virtual public Vehicle//按虚基类继承 {

public:

void run(){cout<<\void stop(){cout<<\};

class Motorcar:virtual public Vehicle//按虚基类继承 {

public:

void run(){cout<<\