[問題] copy constructor跟assignment operator

看板C_and_CPP (C/C++)作者 (Arim5566)時間12年前 (2013/10/24 22:40), 編輯推噓6(601)
留言7則, 3人參與, 最新討論串1/1
各位版友好 最近回來複習了C++ class CExample { public: CExample(){a = 5;b = 6;} CExample(const CExample &rv){printf("copy\n");a = rv.a;b = rv.b;} void operator=(const CExample &rv) { printf("assignment\n"); a = rv.a; b = rv.b; } int a,b; }; CExample a = b; //這個是呼叫copy constructor,為什麼不是呼叫assignment //overloading? a = b; //這個只呼叫assignment overloading function 為什麼會有這樣的差異? 謝謝各位版友的指教 -- ~宅男的四個徵兆~ ∠□ ○ ! * \○/ ★    (○ ? ╦╦└□ " ○□═ □   □> ║║√√ ╦══╦ ∥    |\ 一回家就上PTT 每天想正妹 以當好人為樂 忘記正妹虧欠自己 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 118.171.81.6 ※ 編輯: Arim 來自: 118.171.81.6 (10/24 22:40) ※ 編輯: Arim 來自: 118.171.81.6 (10/24 22:43)

10/24 22:47, , 1F
不是 overloading 而是只有那個 = 是 copy initialize
10/24 22:47, 1F

10/24 22:55, , 2F
賦值跟初始是不同的東西
10/24 22:55, 2F
謝謝.. 因為有等號所以我以為兩個都是assignment.. ※ 編輯: Arim 來自: 118.171.81.6 (10/24 23:04) ※ 編輯: Arim 來自: 118.171.81.6 (10/24 23:07)

10/25 01:00, , 3F
CExample a = b; 等同於 CExample a(b);
10/25 01:00, 3F

10/25 02:51, , 4F
回樓上,其實不一樣
10/25 02:51, 4F

10/25 02:53, , 5F
你把copy ctor宣告explicit比較看看
10/25 02:53, 5F

10/25 03:06, , 6F
T a=b與T a(T(b))等價
10/25 03:06, 6F

10/25 03:07, , 7F
但compiler 可能幫你處理掉
10/25 03:07, 7F
文章代碼(AID): #1IQJ5QNG (C_and_CPP)
文章代碼(AID): #1IQJ5QNG (C_and_CPP)