我看那個 世紀末軟體革命2 呀 ...
第 242 頁有一行:
class int {
public:
...
Int& operator= (const Int&); //注意傳回值必須是參考
為什麼要是參考呀?
又 ...
第 257 頁:
class text {
...
//第三部份:基本輸出介面
...
char& operator[] (int i) { return str[i]; }
char operator[] (int i) const ( return str[i]; }
為何要寫兩次勒??
--
* Origin: ★ 交通大學資訊科學系 BBS ★ <bbs.cis.nctu.edu.tw: 140.113.23.3>
apple = ball = cat; // 把 apple 和 ball 的值設定成和 cat 一樣
// apple = (ball = cat); 先把 cat 的值指定給 ball, 括號內的運算式的值是
// `cat' 再將運算式的值指定給 apple... 那個 Int& 就是那個指定運算式的形態
// (題外話, 你把 operator=() 的傳回值設成 void 的話, 你就不能作
// apple = ball = cat; 的動作, 只能 ball = cat; apple = ball; )
// 若傳回 Int, 會生出一個暫時的 Int 物件, 指定完會消失 (ctor 和 dtor 會
// 各別被呼叫過一次, 在物件的資料很多的時候就會...很慢), 用 Int& 就把
// 自己傳出去, 省掉建構與解構暫時物件的步驟 (要是繼承很多層的話就... ;P)
詳細可以參考 "Effetive C++" 一書 有關 reference 的部份
> class text {
> ...
> //第三部份:基本輸出介面
> ...
> char& operator[] (int i) { return str[i]; }
> char operator[] (int i) const ( return str[i]; }
Ans #2:
一個給 text 形態用... 一個給 `const text' 用...
text not_const_text;
const text const_text;
not_const_text[5] = ch; // ok, change the value because char&
// and the above call `char& operator[]()'
const_text = ch; // error, you cannot change value
// and the above statement calls `char operator[]()'
也是參考上面提到的那本書... 有關 `const'...
你看得滿仔細的喔!
--
Perfection is achieved only on the point of collapse.
- C.N.Parkinson
E-mail : eric...@www.cgu.edu.tw
Homepage : http://www.cgu.edu.tw/~ericosur/
謝謝 ... :P
那 ... 請問若是在最前面加一個 const ...
const char& operator[] (int i) { return str[i]; }
又是代表什麼樣的意思呢?
是說傳回一個 const 物件,他的傳回值是個常數且初值是 str[i] 嗎??
再次謝謝您的回答 ... :)
--
搞不好很久以後,幾年或幾十年後,可以發現得救了的自己。而且那時候,大象回到
平原去,用比我所用的更美好的語言,開始談論這個世界。
-聽風的歌,村上春樹
--
Perfection is achieved only on the point of collapse.
- C.N.Parkinson
E-mail : eric...@www.cgu.edu.tw
Homepage : http://www.cgu.edu.tw/~ericosur/