您好,欢迎访问三七文档
当前位置:首页 > 商业/管理/HR > 市场营销 > C++程序设计实验报告-多态性
《C++程序设计》实验报告Exercise8多态性1实验目的(1)掌握运算符重载的方法。(2)学习使用虚函数实现动态多态性。2.实验要求(1)定义Point类,有坐标_x,_y两个成员变量;对Point类重载“++”(自增)、“――”(自减)运算符,实现对坐标值的改变。源程序代码:#includeiostreamusingnamespacestd;classPoint{public:Point&operator++();Pointoperator++(int);Point&operator--();Pointoperator--(int);Point(){_x=_y=0;}intx(){return_x;}inty(){return_y;}private:int_x,_y;};Point&Point::operator++(){_x++;_y++;return*this;}PointPoint::operator++(int){Pointtemp=*this;++*this;returntemp;}Point&Point::operator--(){_x--;_y--;return*this;}PointPoint::operator--(int){Pointtemp=*this;--*this;returntemp;}intmain(){Pointa;couta的坐标为:(a.x(),a.y())endl;a++;couta的坐标为:(a.x(),a.y())endl;++a;couta的坐标为:(a.x(),a.y())endl;a--;couta的坐标为:(a.x(),a.y())endl;--a;couta的坐标为:(a.x(),a.y())endl;return0;}运行结果:(2)定义一个车(vehiele)基类,有Run、Stop等成员函数,由此派生出自行车(bicycle)类、汽车(motorcar)类,从bicycle和motorcar派生出摩托车(motorcycle)类,它们都有Run、Stop等成员函数。观察虚函数的作用。源程序代码:#includeiostreamusingnamespacestd;classvehicle{public:virtualvoidrun()const{coutvehicle开始运行endl;virtualvoidstop()const{coutvehicle停止运行endl;};classbicycle:publicvehicle{public:voidrun()const{coutbicycle开始运行endl;voidstop()const{coutbicycle停止运行endl;};classmotorcar:publicvehicle{public:virtualvoidrun()const{coutmotorcar开始运行endl;virtualvoidstop()const{coutmotorcar停止运行endl;};classmotorcycle:publicbicycle,publicmotorcar{public:voidrun()const{coutmotorcycle开始运行endl;voidstop()const{coutmotorcycle停止运行endl;};voidfun(vehicle*ptr){ptr-run();ptr-stop();}intmain(){vehiclea;bicycleb;motorcarc;motorcycled;fun(&a);fun(&b);fun(&c);fun(&d);return0;}运行结果:3总结体会要多练习运算符的重载,了解熟悉程序的多态性;虚函数是为访问派生类中与基类同名的成员函数,在基类中将同名函数说明为虚函数后,就可以通过基类类型的指针使属于不同派生类的不同对象产生不同的行为,否则只能是基类的行为;同时也要注意如果一个类派生出两个以上派生类,需注明为虚基类。
本文标题:C++程序设计实验报告-多态性
链接地址:https://www.777doc.com/doc-5592288 .html