[問題] pass by reference的問題

看板C_and_CPP (C/C++)作者 (今年要衝一發)時間16年前 (2009/03/01 20:41), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串1/2 (看更多)
小弟對這邊觀念有點不清楚...希望請大家幫我解答一下 以下為程式碼(compiler是dev-c++ 4.9.9.2) #include <iostream> #include <string> using namespace std; string foo(); int main() { string str = foo(); cout << "address: " << &str << endl << "content: " << str << endl; str = foo(); cout << "address: " << &str << endl << "content: " << str << endl; cout << "address: " << &foo()<< endl << "content: " << foo() << endl; system("pause"); return 0; } string foo() { string s; s = "test"; cout << "In Foo! address: " << &s << endl << "In Foo! content: " << s << endl; return s; } 以下為執行的結果 我一行一行解釋並請各位看我觀念有何問題 In Foo! address: 0x22ff50 In Foo! content: test address: 0x22ff50 content: test 以上四行的str和foo裡面的s記憶體位置一樣 因為創造str時即令他等於foo() 在這種狀況下 雖然沒有指定是return by reference 但compiler仍會自動以reference來傳回 In Foo! address: 0x22ff40 In Foo! content: test address: 0x22ff50 content: test 這四行 因為重新指定str = foo() 所以系統就使用return by value 因此兩個字串變數的記憶體位置當然不一樣 In Foo! address: 0x22ff40 In Foo! content: test In Foo! address: 0x22ff30 In Foo! content: test address: 0x22ff30 content: test 這一塊我就搞不清楚了 一開始碰到&foo()時 先呼叫了一次foo 得到s的記憶體位置是0x22ff40 <--(*) 後來碰到foo() 再次呼叫一次 得到s的記憶體位置為0x22ff30 但最後在main()裡面 得到的&foo()值是0x22ff30 但我覺得奇怪的是 &foo()這個位置 不是應該是先被呼叫的foo()的記憶體位置嗎 那又由(*)的結果顯示 記憶體位置應該是0x22ff40 結果得到的卻是0x22ff30? 我總覺得是哪裡沒搞懂 想了半天想不出來 請大家幫我看看 感謝@@ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.45.229.243
文章代碼(AID): #19geA7OC (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #19geA7OC (C_and_CPP)