资源描述:
《实验六继承与派生》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、继承与组合一、实验目的1.了解继承在面向对象程序设计屮的重要作用。2.进一步理解继承与派生的概念。3.掌握通过继承派生出一个新的类的方法。4.了解虚基类的作用和用法。5.掌握类的组合二、实验内容1.请先阅读下面的程序,写出程序运行的结果,然后再上机运行程序,验证自己分析的结果是否正确。(1)#includeusingnamespacestd;classA{public:A(){cout«uA::A()called.'n”;}virtual~A(){cout«"A::-A()calledAn";}};cl
2、assBipublicA{public:B(inti){cout«HB::B()caHed.M;buf=newchar[i];}virtual~B(){delete[Jbuf;coutvv"B::~B()called.";}private:char*buf;};voidfun(A*a){cout«HMayyousucceed!H«endl;deletea;}intmain(){A*a=newB(15);fun(a);return0;1、(1)程序运行结果:A::A()called.called.Mayyousucc
3、eed!called.A::~A()called.called.B::BOcalled・Mayyousucceed?B::~B<>called・R::~A<>called.frocessexitedwithpeturnualue0ressanykeytocontinue...⑵#includeusingnamespacestd;classA{public:A(inta,intb):x(a),y(b){cout«HAconstructo匚..H«endl;}voidAdd(inta.intb){x+=a;
4、y+=b;)voiddisplay(){cout«',("«x«M,"«y«")H;}-A(){cout«HdestructorA...H«endl;}private:intx,y;};classB:privateA{private:inti,j;AAobj;public:B(inta.intbjntcjntd):A(a,b),i(c)j(d),Aobj(l,l){cout«lfBconstructor...H«endl;}voidAdd(intx1,inty1,intx2,inty2)A::Add(xl,yl);i+=x
5、2;j+二y2;}voiddisplay(){A::display();Aobj.displayO;cout«,,(,,«i«,,;,«j«,,)n«endl;}〜B(){cout«MdestructorB…”vvendl;}};intmain(){Bb(l,2,3,4);b.displayO;b.Add(l,3,5,7);b.displayO;return0;}(1)程序运行结果:Aconstructor...Aconstructor…Bconstructor…(1,2)(1,1)(3,4)(2,5)(1,1)(8,11
6、)destructorB…destructorA…destructorA…⑶#includeusingnamespacestd;classA{public:A(inta):x(a){cout«nAconstructor...n«x«endl;}intf(){return++x;}〜A(){cout«MdestructorA...n«endl;}private:intx;};classB:publicvirtualA{private:inty;AAobj;public:B(inta,intb,intc):
7、A(a),y(c),Aobj(c){cout«nBconstructor...,f«y«endl;)intf(){A::f();Aobj.f();return++y;}voiddisplay(){cout«A::f()«"tn«Aobj.f()«',t"«f()«endl;}〜B(){cout«HdestructorB>..n«endl;}};classC:publicB{public:C(intajntbjntc):B(abc),A(O){cout«nCconstructor...H«endl;}};classD:p
8、ublicC,publicvirtualA{public:D(intajntb,intc):C(a,b,c),A(c){cout«HDconstructor...M«endl;)〜D(){cout«MdestructorD../'«endl;)};intmain(){Dd(7,8,9);d.f();d.