看板 C_and_CPP 關於我們 聯絡資訊
class employee { char *name; // 式中賦值 employee(char* tmp ) { name = tmp; } // 初始化串列 employee(char* tmp):name(tmp) { } } 這二種不是一樣嗎? 請問何時要用初始化串列? 優缺點為何? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 49.214.114.228 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1505871645.A.DC3.html
bluesoul: 式中賦值等於給值兩次。如果成員沒有預設建構子會失敗 09/20 09:48
bluesoul: https://goo.gl/mpWWH2 09/20 09:49
steve1012: 兩個不一樣 09/20 10:36
notBeing: 改成char * const name 試試看 09/20 10:44
asktin: 這樣是不是能用初值串列就不要寫在建構式中 09/20 13:29
stucode: 一般來說是,除非有什麼特別需求。 09/20 13:41
outofyou: 繼承的時候? 09/20 14:06
Richun: 如果class的const變數要初始化 好像只能用初始化串列 09/20 14:17
s4300026: 我都用 foo(char a): a{a} 09/20 18:08
s4300026: 如果變數改成 const,那傳入的是const不知道行不行 09/20 18:11
eye5002003: C++11可以在成員宣告處直接賦值,比寫在建構子更漂亮 09/20 20:33