[問題] 建構子 / 解構子呼叫時間?
開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
Dev C++ 64bit (v5.4.2)
程式碼(Code):(請善用置底文網頁, 記得排版)
http://codepad.org/juGgBuIu
問題(Qusetion):
我自己執行的結果是
Shares = 12 Price = 20 Total = 240
Shares = 2 Price = 2 Total = 4
Bye!
After change:
Shares = 10 Price = 50 Total = 500
Shares = 12 Price = 20 Total = 240
想問的是,(1)解構子裡的輸出"Bye!"是怎麼出現的?
是因為程式碼第50行 test2=test1;
test2物件要把原本的屬性丟掉才能接受test1的,
所以complier對test2物件自動執行~Stock()嗎?
否則不是沒呼叫解構子嗎? 怎麼會忽然執行咧?
另外書上的範例,最後還會有2個"Bye!"出來
Shares = 12 Price = 20 Total = 240
Shares = 2 Price = 2 Total = 4
Bye!
After change:
Shares = 10 Price = 50 Total = 500
Shares = 12 Price = 20 Total = 240
Bye!
Bye!
因為程式要結束了,會對test1, test2物件釋放記憶體,這可以解理
(2)但為何一樣的code,我卻沒有跑出這2個"Bye!"呢?
complier不一樣的關係??
(3)最後一題是19~24行的預設建構子,我把它刪掉,改把成員在private中宣告好
private:
int shares=0;
double price=0.0;
double total=0.0;
程式一樣可以執行,但為何會有Warning呢?
[Warning] non-static data member initializers only available with -std=c++11
or -std=gnu++11 [enabled by default]
剛接觸C++,請多指教,謝謝各位!
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 118.168.182.101
※ 編輯: bizza 來自: 118.168.182.101 (11/06 22:20)
→
11/06 22:21, , 1F
11/06 22:21, 1F
→
11/06 22:25, , 2F
11/06 22:25, 2F
→
11/06 22:25, , 3F
11/06 22:25, 3F
→
11/06 22:30, , 4F
11/06 22:30, 4F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 1 之 2 篇):