資源描述:
《繼承多態(tài)和虛函數(shù)課件.ppt》由會(huì)員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在教育資源-天天文庫。
1、第10章繼承、多態(tài)和虛函數(shù)2021/7/27110.1繼承繼承是OOP程序設(shè)計(jì)中很重要的一個(gè)方面。繼承易于擴(kuò)充現(xiàn)有類以滿足新的應(yīng)用。將已有的類稱之為父類,也稱基類,將新產(chǎn)生的類稱為子類,也稱為導(dǎo)出類或派生類。派生類不做任何改變地繼承了基類中的所有變量和函數(shù)(構(gòu)造函數(shù)和析構(gòu)函數(shù)除外),并且還可以增加新的數(shù)據(jù)成員和函數(shù),從而使導(dǎo)出類比基類更為特殊化。Example:例10-1.2021/7/272//Contentsofgrade.hclassGrade{charletter;floatscore;voidcalcGrade();public:voidsetScore(floats){s
2、core=s;calcGrade();}floatgetScore(){returnscore;}chargetLetter(){returnletter;}};2021/7/273//Contentsofgrade.cpp#include"grade.h"http://DefinitionofmemberfunctionGrade::calcGradevoidGrade::calcGrade(){if(score>89)letter='A';elseif(score>79)letter='B';elseif(score>69)letter='C';elseif(score>59)letter
3、='D';elseletter='F';}2021/7/274//Contentsoftest.h#include"grade.h"classTest:publicGrade{intnumQuestions;floatpointsEach;intnumMissed;public:Test(int,int);};2021/7/275//Contentsoftest.cpp#include"test.h"http://參數(shù)q代表問題的個(gè)數(shù),m代表答錯(cuò)的題數(shù).Test::Test(intq,intm){floatnumericGrade;numQuestions=q;numMissed=m;poin
4、tsEach=100.0f/numQuestions;numericGrade=100.0f-numMissed*pointsEach;setScore(numericGrade);}2021/7/276#include"test.h"voidmain(){intquestions,missed;cout<<"Howmanyquestions?";cin>>questions;cout<<"Howmanyquestionsmissed?";cin>>missed;Testexam(questions,missed);cout.precision(2);cout<<"Thescor
5、eis"<6、.2保護(hù)成員和類的訪問基類中的保護(hù)成員和私有成員比較類似,唯一的區(qū)別是:子類不可訪問基類中的私有成員,但可訪問基類中的保護(hù)成員。在公有繼承或保護(hù)繼承的情況下,子類能訪問基類的protected成員。Example:例10-22021/7/279//Contentsofgrade2.hclassGrade{protected:charletter;floatscore;voidcalcGrade();public:voidsetScore(floats){score=s;calcGrade();}floatgetScore(){returnscore;}chargetLetter(){
7、returnletter;}};2021/7/2710//Contentsoftest2.h#include"grade2.h"classTest:publicGrade{intnumQuestions;floatpointsEach;intnumMissed;public:Test(int,int);voidadjustScore();//新增加的函數(shù)};2021/7/2711//Contentsoftest2.cpp#include"test2.h"/