EasyC++,類的實(shí)現(xiàn)
大家好,我是梁唐。
想要追求更好閱讀體驗(yàn)的同學(xué),可以點(diǎn)擊「閱讀原文」訪問github倉庫。
類的實(shí)現(xiàn)
當(dāng)我們完成了類定義之后, 還需要來實(shí)現(xiàn)類當(dāng)中的函數(shù)。
比如我們?cè)趕tock00.h當(dāng)中定義了一個(gè)類:
- #ifndef STOCK00_H_
 - #define STOCK00_H_
 - #include <string>
 - class Stock {
 - private:
 - std::string company;
 - long shares;
 - double share_val;
 - double total_val;
 - void set_tot() {total_val = shares * share_val;}
 - public:
 - void accquire(const std::string &co, long n, double pr);
 - void buy(long num, double price);
 - void sell(long num, double price);
 - void update(double price);
 - void show();
 - };
 - #endif
 
成員函數(shù)
在這個(gè)定義當(dāng)中,我們只是聲明了函數(shù),并沒有具體實(shí)現(xiàn)函數(shù)的邏輯。
我們通常會(huì)在同名的cpp文件當(dāng)中實(shí)現(xiàn),實(shí)現(xiàn)的時(shí)候,需要使用作用域解析運(yùn)算符來表示函數(shù)所屬的類:
- void Stock::update(double price) {
 - ...
 - }
 
這樣就表明了update函數(shù)所屬Stock這個(gè)類,這也就意味著我們可以創(chuàng)建屬于其他類的同名函數(shù):
- void Buffoon::update() {
 - ...
 - }
 
其次,我們?cè)诔蓡T函數(shù)當(dāng)中,可以訪問private限定的成員變量。比如說在show函數(shù)當(dāng)中,我們可以這樣實(shí)現(xiàn):
- void Stock::show() {
 - std::cout << company << shares << share_val << total_val << endl;
 - }
 
雖然company,shares都是類的私有成員,但在成員方法當(dāng)中,一樣可以正常訪問。
再次,我們?cè)诔蓡T方法當(dāng)中調(diào)用另外一個(gè)成員方法,可以不需要解析運(yùn)算符。比如我們要在show函數(shù)內(nèi)調(diào)用update函數(shù),直接使用update()即可,而無需前面的Stock::。
內(nèi)聯(lián)函數(shù)
我們?cè)倩剡^頭來看一下Stock這個(gè)類的定義,在類的定義當(dāng)中,有一個(gè)叫做set_tot的函數(shù)。我們直接在類當(dāng)中實(shí)現(xiàn)了邏輯。雖然同樣是成員函數(shù),但是在類當(dāng)中直接實(shí)現(xiàn)的函數(shù)是有所區(qū)別的。在類聲明當(dāng)中實(shí)現(xiàn)的函數(shù),會(huì)被視為是內(nèi)聯(lián)函數(shù)。
一般我們會(huì)把一些比較簡短的函數(shù)在類的聲明當(dāng)中直接實(shí)現(xiàn),當(dāng)然我們也可以使用關(guān)鍵字inline,手動(dòng)指定某個(gè)函數(shù)是內(nèi)聯(lián)的。
- class Stock {
 - private:
 - void set_tot();
 - public:
 - ...
 - };
 - inline void Stock::set_tot() {
 - total_val = shares * share_val;
 - }
 
本文轉(zhuǎn)載自微信公眾號(hào)「Coder梁」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請(qǐng)聯(lián)系Coder梁公眾號(hào)。
















 
 
 
 
 
 
 