先解釋const 的記憶問(wèn)題:
比如:
type const * p;
* p 是表示對(duì)象, const 修飾 *p , 就表示常對(duì)象。即 *p 對(duì)象不可改變。 所以 p 不是 常指針,是指向常量的指針。
相對(duì)于:const type * const * p; 的寫(xiě)法,個(gè)人推薦前一種。
而:
type * const p;
const 修飾 p, 所以 p 是常量,而* const p 即代表指針常量. p 是常指針。
所以
int * & func(C &oC)
{
return oC.m_p;
}
表示返回指針的引用
但沒(méi)有:
int & * func(C &oC)
{
return oC.m_p;
}
編譯器會(huì)把 int & * 中的 & 看作取地址符號(hào)。
如果要對(duì) int 型變量進(jìn)行應(yīng)用,為沒(méi)必要這樣
可以這樣寫(xiě):
int & func(C &oC)
{
return *oC.m_p;
}
同樣記憶:
常引用對(duì)象: type const & Ref ;
還要注意const 修飾函數(shù)只能是 類成員函數(shù),而不能是全局函數(shù)