C++语言程序设计实验报告 10.docx
- 文档编号:26259985
- 上传时间:2023-06-17
- 格式:DOCX
- 页数:15
- 大小:90.31KB
C++语言程序设计实验报告 10.docx
《C++语言程序设计实验报告 10.docx》由会员分享,可在线阅读,更多相关《C++语言程序设计实验报告 10.docx(15页珍藏版)》请在冰豆网上搜索。
C++语言程序设计实验报告10
C++语言程序设计实验报告
基础题一
实验任务:
定义一个哺乳动物Mammal类,再由此派生出狗Dog类,二者都定义Speak()成员函数,基类中定义为虚函数,定义一个Dog类的对象,调用Speak函数,观察运行结果。
代码:
#include
usingnamespacestd;
classAnimal
{
public:
virtualvoidSpeak();
};
voidAnimal:
:
Speak()
{
cout<<"Animal中的SPEAK()函数被调用";
}
classDog:
virtualpublicAnimal
{
public:
virtualvoidSpeak();
};
voidDog:
:
Speak()
{
cout<<"Dog中的SPEAK()函数被调用"< } voidmain() { DogDog1; Dog1.Speak(); } 结果: 基础题二 实验任务: 对Point类重载++(自增)、--(自减)运算符 代码: #include usingnamespacestd; classPoint { public: Point(intx=0,inty=0){this->x=x;this->y=y;} voidshow(); Point&operator++(); Pointoperator++(int); Point&operator--(); Pointoperator--(int); private: intx,y; }; voidPoint: : show() { cout<<"该点坐标为"<<"("< } Point&Point: : operator++() { x++; y++; return*this; } PointPoint: : operator++(int) { Pointold=*this; ++(*this); returnold; } Point&Point: : operator--() { x--; y--; return*this; } PointPoint: : operator--(int) { Pointold=*this; --(*this); returnold; } intmain() { PointmyPoint(1,3); cout<<"第一次输出"; myPoint.show(); cout<<"ShowmyPoint++: "; (myPoint++).show(); cout<<"Show++myPoint: "; (++myPoint).show(); cout<<"ShowmyPoint--: "; (myPoint--).show(); cout<<"Show--myPoint: "; (--myPoint).show(); return0; } 结果: 提高题一 实验任务: 设计一个字符串类MyString,具有构造函数、析构函数、拷贝构造函数,重载运算符+,尽可能地完善它,使之能满足各种需要。 代码: #include #include classperson { public: person(char*pn); person(person&p); ~person(); private: char*pname; }; person: : person(char*pn) { cout<<"构造函数: "< pname=newchar[strlen(pn)+1]; if(pname! =0) strcpy(pname,pn); } person: : person(person&p) { cout<<"拷贝"< pname=newchar[strlen(p.pname)+1]; if(pname! =0) strcpy(pname,p.pname); } person: : ~person() { cout<<"析构函数: "< pname[0]='\0'; deletepname; } voidmain() { personp1("jack"); personp2(p1); } 结果: 提高题二 实验任务: 声明一个Shape抽象类,再此基础上派生出Rectangle和Circle类,二者都有GetArea()函数计算对象的面积,GetPerim()函数计算对象的周长。 代码: #include usingnamespacestd; #definen3.14 classShape { public: virtualvoidGetArea()=0; virtualvoidGetPerim()=0; }; classRectangle: publicShape { public: Rectangle(inta,intb){this->a=a;this->b=b;} voidGetArea(); voidGetPerim(); private: inta,b; }; voidRectangle: : GetArea() {
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- C+语言程序设计实验报告 10 C+ 语言程序设计 实验 报告
![提示](https://static.bdocx.com/images/bang_tan.gif)