[問題] 請問最後destructure沒輸出?

看板C_and_CPP (C/C++)作者 (adonis)時間16年前 (2009/06/02 14:21), 編輯推噓2(207)
留言9則, 3人參與, 最新討論串1/1
#include<iostream> #include<iomanip> #include<cmath> using namespace std; class Resistor { float r1; public: Resistor(float a) { r1=a; } friend ostream&operator<<(ostream &val,Resistor &re) { //或者在開個副程式寫 cout<<"Repeat:\n\nInput Resistance(kΩ) = "<<re.r1<<" kΩ"<<endl; } ~Resistor() { cout<<"Resistor is destoryed."<<endl; } }; class Circuit { float current,voltage; public: Resistor r2; Circuit(float a,float va3):r2(a) { voltage=va3; current=va3/a; } friend ostream &operator<<(ostream &va2,Circuit &i) { cout<<i.r2; cout<<"Input Voltage(V) = "<<i.voltage<<" V\n"<<endl; cout<<"calculated Current = "<<i.current<<" mA"<<endl; } ~Circuit() { cout<<"Circuit is destroyed."<<endl; } }; int main() { float rin,vin; cout<<"Input the Resistance (kΩ): "; cin>>rin; cout<<"Input the Voltage (V) : "; cin>>vin; Circuit C(rin,vin); cout<<C; system("pause"); return 0; } ================以上為程式碼==================== 我想要的結果是印出Circuit(電流) 和circuit及resistor兩者destroyed的結果 但最後兩沒有出現上述二者毀滅的輸出 請問是哪出錯了呢 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 120.107.174.108

06/02 14:30, , 1F
把 Circuit 與 cout<<C 這兩行用 { } 括起來呢??
06/02 14:30, 1F

06/02 14:36, , 2F
呃 你pause住了@@
06/02 14:36, 2F
可是如果我用下面這個的話就可以 #include<iostream> #include<iomanip> using namespace std; class Resistor { float r; public: Resistor(float x) { r=x; } friend ostream &operator<<(ostream &str,Resistor obj) { cout<<"Resistance = "<<obj.r<<" Ω\n"; } ~Resistor() { cout<<"Resistor is destroyed.\n"; } }; class Circuit { Resistor r; float current,voltage; public: Circuit(float x,float y):r(x) { voltage=y; current=y/x; } friend ostream &operator<<(ostream &str,Circuit obj) { cout<<obj.r; cout<<"Current = "<<obj.current<<" A\n"; cout<<"Voltage = "<<obj.voltage<<" V\n"; } ~Circuit() { cout<<"Circuit is destroyed.\n"; } }; int main() { float r,v; cout<<"Please input the Resistance: "; cin>>r; cout<<"Please input the Voltage: "; cin>>v; Circuit c(r,v); cout<<endl<<c; system("pause"); return 0; } 下面這個也有pause不是嗎? ※ 編輯: adoniscomes 來自: 120.107.174.108 (06/02 14:41)

06/02 14:42, , 3F
喔 感謝vic大 可以了 十分感謝!!m(_._)m
06/02 14:42, 3F

06/02 14:44, , 4F
c是local變數, 所以main()結束後才會被釋放掉call dtor
06/02 14:44, 4F

06/02 14:45, , 5F
這時你的PAUSE起來時c其實還活著, 所以dtor還沒叫到:)
06/02 14:45, 5F

06/02 14:45, , 6F
加{}只是測一下, 如果您希望準確的控制obj生死, 就要考
06/02 14:45, 6F

06/02 14:46, , 7F
律new/delete了, 不過您可能會需要多寫default ctor與
06/02 14:46, 7F

06/02 14:46, , 8F
其他set函數:p
06/02 14:46, 8F

06/02 14:50, , 9F
課本內似乎有V大說的類似 原來是這種關係 了解(_._)
06/02 14:50, 9F
文章代碼(AID): #1A9CJTYR (C_and_CPP)
文章代碼(AID): #1A9CJTYR (C_and_CPP)