iT邦幫忙

0

C++ Primer 5th Edition Exercises(練習題)13.18

練習13.18

Define an Employee class that contains an employee name and a unique employee identifier. Give the class a default constructor and a constructor that takes a string representing the employee’s name. Each constructor should generate a unique ID by incrementing a static data member.

定義一個名為Employee的類別,它包括了員工的名字和一個唯一的員工識別證號碼。請給這個類別定義一個預設建構器,還有一個建構器是帶了一個string型別的參數用來表示員工的名字。這二個建構器都應該要能夠藉由遞增一個靜態的資料成員來產生一個唯一的識別號碼。【為什麼要用靜態?因為靜態成員的生命週期是在一經配置後就會保留到整個應用程式結束時才會結束;因此只要我們不會去歸零它,它的值就永遠不會歸零;但要注意若在下次啟動應用程式時,一定要有一個讀取最後值的機制來賦予給它,否則就會從零開始遞增,那就必然會有重複值了】

忘了錄的部分臉書直播第535集約10分鐘前後

#include<iostream>
using namespace std;
struct Employee {
//public:
    Employee() :ID(++myID),employeeName("十方三世佛,共同一法身,一心一智慧,力無畏亦然"){};
    Employee(const string& employeeName) :ID(++myID),employeeName(employeeName) {};
    const string employeeName;
    const unsigned ID;
private:
    static unsigned myID;//此類似宣告-配置資源(宣告類別內的靜態成員)
};
unsigned Employee::myID = 0;/*此類似定義-建構實例,初始化已經宣告的類別靜態成員
如何初始化靜態資料成員
                            https://openhome.cc/Gossip/CppGossip/staticMember.html 
                            static 資料成員屬於類別,而非個別實例,想在類別內初始 static 資料成員的話,必須是個 constexpr,也就是必須是編譯時期常數,若否,必須在類別外指定,例如:
                            class Math {
                            public:
                                static double PI;
                            };
                            double Math::PI = 3.14159;
                            */

void f(Employee s) { cout << s.employeeName << "'s ID is :"<< s.ID << endl; }
int main() {    
    Employee a,b("孫守真"),c("阿彌陀佛");
    f(a);f(b); f(c);
}

https://github.com/oscarsun72/prog1-C-Primer-5th-Edition-s-Exercises/blob/exercise13_18/prog1/prog1.cpp


C++自修入門實境秀 535 重新譯撰 《C++ Primer 5th》
13.1.6. 制斷拷貝 練習13.18~
上一集:
https://www.facebook.com/100003034306665/videos/2641474629296988
下一集:
全部:http://bit.ly/2NoA2ID 原檔下載:http://bit.ly/2Ixe2Vc
課文: http://bit.ly/2FIHV57
http://bit.ly/2mttmfa(第二篇)
第10-11章: http://bit.ly/2MuPmiZ
章12: http://bit.ly/2Rw53sH
重譯12章:http://bit.ly/2V8UgZ7
http://bit.ly/2G2fPSg (docx)
重譯11章:http://bit.ly/39P7HRU
第三篇:http://bit.ly/2UaFbDY
第三篇13章:http://bit.ly/33mh49y

https://play.google.com/books/reader?id=J1HMLyxqJfgC&pg=GBS.PT940.w.4.0.73

講義下載:
http://bit.ly/2khF8Ic (全部)
程式碼:
https://github.com/oscarsun72/prog1

緣起:http://bit.ly/2XwHOUH


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言