C++实验三继承和派生类附答案.docx
- 文档编号:8947990
- 上传时间:2023-05-16
- 格式:DOCX
- 页数:28
- 大小:85.40KB
C++实验三继承和派生类附答案.docx
《C++实验三继承和派生类附答案.docx》由会员分享,可在线阅读,更多相关《C++实验三继承和派生类附答案.docx(28页珍藏版)》请在冰点文库上搜索。
C++实验三继承和派生类附答案
实验三继承和派生类
实验目的和要求
1.理解类的继承的概念,能够定义和使用类的继承关系。
2.掌握派生类的声明与定义方法。
3.熟悉公有派生和私有派生的访问特性。
4.学习虚基类在解决二义性问题中的作用。
实验内容
1.先阅读下面的程序,分析程序运行的结果,然后再上机运行程序,验证自己分析的结果是否正确。
(1)
#include
classA
{
public:
A()
{
cout<<"A:
:
A()called.\n";
}
~A()
{
cout<<"A:
:
~A()called.\n";
}
};
classB:
publicA
{
public:
B(inti)
{
cout<<"B:
:
B()called.\n";
buf=newchar[i];
}
~B()
{
delete[]buf;
cout<<"B:
~B()called.\n";
}
private:
char*buf;
};
voidmain()
{
Bb(10);
}
(2)
#include
classA
{
public:
A(inta,intb):
x(a),y(b)
{
cout<<"Aconstructor..."< } voidAdd(inta,intb) { x+=a; y+=b; } voiddisplay() { cout<<"("< } ~A() { cout<<"destructorA..."< } private: intx,y; }; classB: privateA { private: inti,j; AAobj; public: B(inta,intb,intc,intd): A(a,b),i(c),j(d),Aobj(1,1) { cout<<"Bconstructor..."< } voidAdd(intx1,inty1,intx2,inty2) { A: : Add(x1,y1); i+=x2; j+=y2; } voiddisplay() { A: : display(); Aobj.display(); cout<<"("< } ~B() { cout<<"destructorB..."< } }; voidmain() { Bb(1,2,3,4); b.display(); b.Add(1,3,5,7); b.display(); } (3) #include classA { public: A(inta): x(a) { cout<<"Aconstructor..."< } intf() { return++x; } ~A() { cout<<"destructorA..."< } private: intx; }; classB: publicvirtualA { private: inty; AAobj; public: B(inta,intb,intc): A(a),y(c),Aobj(c) { cout<<"Bconstructor..."< } intf() { A: : f(); Aobj.f(); return++y; } voiddisplay() { cout< : f()<<'\t'< } ~B() { cout<<"destructorB..."< } }; classC: publicB { public: C(inta,intb,intc): B(a,b,c),A(0) { cout<<"Cconstructor..."< } }; classD: publicC,virtualpublicA { public: D(inta,intb,intc): C(a,b,c),A(c) { cout<<"Dconstructor..."< } ~D() { cout<<"destructorD..."< } }; voidmain() { Dd(7,8,9); d.f(); d.display(); } (4) #include classBase1 { public: Base1() { cout<<"classBase1! "< } }; classBase2 { public: Base2() { cout<<"classBase2!
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- C+ 实验 继承 派生 答案
![提示](https://static.bingdoc.com/images/bang_tan.gif)