作者ric2k1 (Ric)
看板EE_DSnP
標題Re: [問題] const
時間Sun Apr 12 23:53:44 2009
※ 引述《dxi (D差耶)》之銘言:
: 觀念不大清楚,煩請老師與各位同學指教:
: Passed in a reference to a constant object ‘c’
: 'c' cannot be modified in the function
: ↓
: const A& B::blah (const C& c) const{...}
: ↑ ↑
: Return a reference to a ↑
: constant object ↑
: → The returned object can ↑
: then only call constant methods ↑
: ↑
: This is a constant method, meaning this object is
: treated as a constant during this function
: →None of its data members can be modified
: 請問上述的const method是指傳回主程式的物件是const嗎?
: 謝謝
分三種情形來討論:
1.
B b;
b.blah().kk(); // kk() 是 class A 的 member function
--------
↑
因為 return 的是一個 const A&, 所以它會被視為 const object, 而只能呼叫
class A 的 const methods, 也就是說, kk() 必定是一個 const member function
2.
B b;
const A& a = b.blah();
a.kk();
跟上面的情形相似, 只不過我們用一個 reference variable a 將 return 的 object
參照下來, 所以 a 必須為 const A&, 且只能呼叫 const methods.
3.
B b;
A a = b.blah();
a.kk();
注意這裡做的是 '=' (copy), 雖然 b.blah() return 了一個 const A&,
但是 A a 做了一份 copy, 所以 A a 可以不用是 const, 也可以呼叫 non-const
methods. (Think: 就像是 int i = 10; <== const copy 給一個 non-const
variable).
不過要注意的是 a 呼叫 kk() 之後的作用是在 a 身上, 跟 b.blah() return
的那個 object 已經沒有關係了.
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 61.216.0.233
1F:推 dxi:謝謝老師 04/13 01:23