您好,欢迎访问三七文档
当前位置:首页 > 商业/管理/HR > 其它文档 > c++继承与派生实验报告
第七章继承与派生实验目的学习声明和使用类的继承关系,声明派生类熟悉不同继承方式下对基类的访问控制学习使用虚基类解决二义性问题实验内容7.1#includeiostreamusingnamespacestd;classanimal{public:private:intage;};classdog:publicanimal{public:voidsetage(intn);private:};voiddog::setage(intn){age=n;}intmain(){dogd1;d1.setage(5);return0;}无法访问age,因为公有继承的继承规则是基类的私有类不可访问、#includeiostreamusingnamespacestd;classanimal{public:intage;private:};classdog:publicanimal{public:voidsetage(intn);private:};voiddog::setage(intn){age=n;}intmain(){dogd1;d1.setage(5);return0;}把age移到private里即可7.2#includeiostreamusingnamespacestd;classbaseclass{public:baseclass(intn){number=n;cout调用了基类的构造函数endl;}~baseclass(){cout调用了基类的析构函数endl;}private:intnumber;};classderivedclass:publicbaseclass{public:derivedclass(intn):baseclass(n){cout调用了派生类的构造函数endl;}~derivedclass(){cout调用了派生类的析构函数endl;}private:};intmain(){derivedclassd(3);return0;}7.3#includeiostreamusingnamespacestd;classvehicle{public:voidrun();voidstop();vehicle(intm,intw){maxspeed=m;weight=w;}private:intmaxspeed;intweight;};voidvehicle::run(){coutitisrunningendl;}voidvehicle::stop(){coutstopendl;}classbicycle:publicvehicle{public:bicycle(intm,intw,inth):vehicle(m,w){height=h;}private:intheight;};classmotorcar:publicvehicle{public:motorcar(intm,intw,ints):vehicle(m,w){seatnum=s;}private:intseatnum;};classmotorcycle:publicbicycle,publicmotorcar{public:motorcycle(intm,intw,inth,ints):vehicle(m,w),bicycle(m,w,h),motorcar(m,w,s){}};intmain(){motorcyclecat(1,2,3,4);cat.run();cat.stop();return0;}不设虚基类报错指代不明是哪一层函数#includeiostreamusingnamespacestd;classvehicle{public:voidrun();voidstop();vehicle(intm,intw){maxspeed=m;weight=w;}private:intmaxspeed;intweight;};voidvehicle::run(){coutitisrunningendl;}voidvehicle::stop(){coutstopendl;}classbicycle:virtualpublicvehicle{public:bicycle(intm,intw,inth):vehicle(m,w){height=h;}private:intheight;};classmotorcar:virtualpublicvehicle{public:motorcar(intm,intw,ints):vehicle(m,w){seatnum=s;}private:intseatnum;};classmotorcycle:publicbicycle,publicmotorcar{public:motorcycle(intm,intw,inth,ints):vehicle(m,w),bicycle(m,w,h),motorcar(m,w,s){}};intmain(){motorcyclecat(1,2,3,4);cat.run();cat.stop();return0;}
本文标题:c++继承与派生实验报告
链接地址:https://www.777doc.com/doc-5592313 .html