C++繼承的標(biāo)準(zhǔn)寫法:
郊區(qū)網(wǎng)站制作公司哪家好,找創(chuàng)新互聯(lián)!從網(wǎng)頁設(shè)計、網(wǎng)站建設(shè)、微信開發(fā)、APP開發(fā)、成都響應(yīng)式網(wǎng)站建設(shè)等網(wǎng)站項目制作,到程序開發(fā),運(yùn)營維護(hù)。創(chuàng)新互聯(lián)自2013年起到現(xiàn)在10年的時間,我們擁有了豐富的建站經(jīng)驗(yàn)和運(yùn)維經(jīng)驗(yàn),來保證我們的工作的順利進(jìn)行。專注于網(wǎng)站建設(shè)就選創(chuàng)新互聯(lián)。
class BaseMonster { public: string name; string skill; uint32_t hp; void attack() { cout << "Base :: 發(fā)動***" << endl; } }; class RedDemonKing : public BaseMonster { } ;
解析:
① 類 RedDemonKing 集成了 類BaseMonster
② 集成的限定詞為 public->
③ 對限定詞的解析->
采用降級處理 : 級別從高到低(降序) public , protected , private 。如采用public,則基類中比public高的成員,全部降一級(因?yàn)闆]有比public高的級別 , 所以都不降級。但是protected的話 , 基類中的public在子類中的訪問級別就降了一級變成protected)。
④ 如果省略繼承的限定詞,則默認(rèn)為private限定詞。
具體:
一,繼承構(gòu)造函數(shù)的調(diào)用順序->先調(diào)用父類的構(gòu)造函數(shù),再調(diào)用子類(自己)的構(gòu)造函數(shù)
1,當(dāng)基類的構(gòu)造函數(shù)為無參構(gòu)造:
#include <iostream> using namespace std; class BaseMonster { public: string name; string skill; uint32_t hp; void attack() { cout << "Base :: 發(fā)動***" << endl; } }; class RedDemonKing : public BaseMonster { } ; int main() { RedDemonKing rdk; rdk.name = "赤妖王"; cout << rdk.name << endl; return 0; }
2,當(dāng)基類有有參數(shù)的構(gòu)造函數(shù)時:
#include <iostream> using namespace std; class BaseMonster { public: string name; string skill; BaseMonster( string name ) { this->name = name; } void attack() { cout << "Base :: 發(fā)動***" << endl; } }; class RedDemonKing : public BaseMonster { public: RedDemonKing( string name ) : BaseMonster(name) { this->skill = "會心一擊"; } } ; int main() { RedDemonKing rdk("赤妖王"); cout << rdk.name << endl; return 0; }
解析:
① RedDemonKing( string name ) : BaseMonster(name) , 以此格式(參數(shù)列表)為調(diào)用基類構(gòu)造。
二,覆蓋
#include <iostream> using namespace std; class BaseMonster { public: string name; string skill; BaseMonster( string name ) { this->name = name; } void attack() { cout << "Base :: 發(fā)動***" << endl; } }; class RedDemonKing : public BaseMonster { public: string name; RedDemonKing( string name ) : BaseMonster(name) { this->name = "赤妖王"; this->skill = "會心一擊"; } } ; int main() { RedDemonKing rdk("妖怪"); cout << rdk.name << endl; cout << rdk.BaseMonster::name << endl; return 0; }
解析:
① 當(dāng)子類和基類有相同名字的成員如上(name),那么子類的name就對積累的name形成了覆蓋(相當(dāng)與作用域)
② 默認(rèn)取值 rdk.name , 取得是子類(自己)的值 。 如果要取基類的值需指定域 : rdk.BaseMonster::name
③ 重點(diǎn) , 只要是名字一樣都會形成覆蓋,不存在重載:
要調(diào)用基類的函數(shù) 必須指定域
firend(友元)不能被繼承( 可以這么理解 : 父親的朋友 , 不一定是自己的朋友 )
文章題目:C++繼承(一)
標(biāo)題鏈接:http://chinadenli.net/article14/geoige.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供企業(yè)網(wǎng)站制作、網(wǎng)站導(dǎo)航、外貿(mào)建站、網(wǎng)站營銷、全網(wǎng)營銷推廣、自適應(yīng)網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)