1、程序名:1ab8_1Cpp#include using namespace std;class Pointpublic:Point();Point(int x,int y);Point() /Point类析构函数Point& operator+(); /公有成员函数Point operator+(int);operator-();Point operator-(int);void Show();private:int _x; /私有数据成员 int _y;Point:Point() /Point类构造函数_x=0;_y=0;Point(int x,int y) /Point类构造函数_x=x;
2、_y=y;Point & Point:operator+() /重载后置+运算符为Point类成员函数_x+;_y+;Point Point:operator+(int) /重载前置+运算符为Point类成员函数Point old=*this;+(this-_x);_y);return old;operator-() /重载后置-运算符为Point类成员函数_x-;_y-;operator-(int) /重载前置-运算符为Point类成员函数-(this-void Point:Show() /输出Point的坐标值 cout_x,_y)endl;int main()Point a(2,3);
3、/定义一个Point类对象aPoint b=a+; /定义Point类对象b并用a+初始化bPoint c=+a; /定义Point类对象c并用+a初始化cPoint d=-a; /定义Point类对象d并用-a初始化dPoint e=a-; /定义Point类对象e并用a-初始化ecoutPoint a(;a.Show(); /输出a的坐标Point b(b.Show(); /输出b的坐标Point c(c.Show(); /输出c的坐标Point d( d.Show(); /输出d的坐标Point e(e.Show(); /输出e的坐标return 0;运行结果:2编写程序定义一个车(ve
4、hicle)基类,有Run、Stop等成员函数,由此派生出自行车(bicycle)类、汽车(motorcar)类,从bicycle和motorcar派生出摩托车(motorcycle)类,它们都有Run、Stop等成员函数。在main()函数中定义vehicle、bicycle、motorcar、motorcycle的对象,调用其Run()、Stop()函数,观察其执行情况。再分别用vehicle类型的指针来调用这几个对象的成员函数,看看能否成功;把Run、Stop定义为虚函数,再试试看。lab8_2cppclass vehicle /基类vehiclevehicle()vehicle()vi
5、rtual void Run()coutThe vehicle is running! /定义虚函数Run()virtual void Stop()coutThe vehicle has stopped! /定义虚函数Stop()class bicycle: virtual public vehicle /定义派生类bicycle,声明基类为派生类的虚基类void Run()coutThe bicycle is running!void Stop()coutRun(); /通过指针调用vehicle类成员函数Stop();b; /使指针p指向bicycle类对象b /通过指针调用bicycle类成员函数c; /使指针p指向motorcar类对象c /通过指针调用motorcar类成员函数d; /使指针指向motorbicycle类对象d /通过指针调用motorcycle类成员函数 源程序:stringclass Birthday Birthday(int Year,int Month,int Day); /构造函数
copyright@ 2008-2022 冰豆网网站版权所有
经营许可证编号:鄂ICP备2022015515号-1