Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

問一題 C++ 程式...

0 views
Skip to first unread message

雙魚殺手

unread,
Feb 14, 2001, 11:00:29 PM2/14/01
to
※ 引述《maninmi...@bbs.csie.nctu.edu.tw (lost world)》之銘言:
> #include <iostream>
> #include <string>
> using namespace std ;
> class Test
> {
> public:
> int &m_ri;
> public:
> Test(int ri) : m_ri(ri)
> {
> }
> void display()
> { cout << "m_ri=" << m_ri << endl ; }
> };
> int main()
> {
> Test t(1);
> t.display();
> return 0;
> }
> display 後, why m_ri不是 1 ?
> thx
即然你誠心誠意的發問了,那我就大發慈悲的告訴你吧…

首先,m_ri 在你 display() 方法執行後,結果不是一的有
兩個關鍵.....第一個就是你屬性宣告成 int &m_ri ,而不是 int m_ri...
第二個就是,在建構子中 Test(int ri):m_ri(ri) 這一行得到的是 ri 的參考..
說明白一點:
就是『在建構子初使化之後』,再『建構子執行結束』之前,其實 m_ri 的值是 = 1
但在建構子執行結束後,因為 ri (這是區域變數) 所佔的記憶體會被釋放掉...
而 m_ri 的 ri 因為消失了...所以得到的是不具任何意義的值...
啥?看不懂我的說明?那看看我修改你的程式碼吧...

#include <iostream>
#include <string>
using namespace std ;

class Test
{
public:
int &m_ri;
public:
Test(int ri) : m_ri(ri)
{
cout << "ri =" << ri << endl;
cout << "&ri =" << &ri << endl;
cout << "m_ri =" << m_ri << endl;
cout << "&m_ri=" << &m_ri << endl << endl;
}

void display()
{
cout << "m_ri =" << m_ri << endl;
cout << "&m_ri=" << &m_ri << endl;
}
};

以上程式碼大致上跟你原來的一樣...不過是加了幾行輸出罷了...
執行結果如下:

ri =1
&ri =006BFDA4
m_ri =1
&m_ri=006BFDA4

m_ri =4199882
&m_ri=006BFDA4

以上有兩個部份...
第一個部份,是當建構子初使化時,ri 的值被設定為 1,而 m_ri 的位址被設定
成為 ri 相同....因為這時就形同函數的傳參考方式...

第二部份,因為 ri 是區域變數,隨著建構子的結束而被釋放掉記憶體,記憶體
被釋放,頂多是值消失了,但位址還是在的啦....
所以 m_ri 之所以不為 1 是因為它與 ri 共用記憶體,而這個值是因 ri 而消失的.
--
》 � 》 《 《
》》 》》 ○ 《《 《《
》》》 ︷︷》》》_ ○ ○ _《《《︷︷ 《《《
》》︽ / ))))◎\ O O /◎﹙﹙﹙﹙ \︽《《
》》︾ \ ))))__< 。 。 >__﹙﹙﹙﹙ /︾《《
》 `````》》 -=[魚兒]=- 《《````` 《
--
[1;33m※ Origin: [36m奇摩 大摩域 [37m<telnet://bbs.kimo.com.tw> [m
[1;35m◆ From: [1;32m210.68.58.205 [m

0 new messages