條款03:儘可能使用 const 【讀書筆記 Effective C++】

基礎知識:
(1)編譯器會保證const修飾不可改變的約束
//tip 1:
char greeting[] = "Hello";
const char* p = greeting;
greeting[1] = 'x'; // wrong
p[1] = 'x';            // correct
 
//tip 2:
const char*p  //表示被指物是常量
char* const p //表示指針自身是常量
 
(2)const對函數聲明的應用
    a. const修飾函數返回值
class Rational {...};
const Rational operator* (const Rational& lhs, const Rational& rhs);
 
Rational a, b, c;
(a * b) = c;//由於上述operator* 返回const,那麼該錯誤的賦值會被編譯器禁止
    b. const成員函數
兩個成員函數的常量性不同,可以被重載,如下例子:
class TextBlock {
public:
    const char& operator[] (int pos) const
    { return text[pos]; }
 
    char &operator[] (int pos)
    { return text[pos]; }
 
private:
    string text;
}
 
注意:
a. 上面例子函數後面的const才支持重載,返回值的const不能支持重載
b. 如果函數返回值是的內置類型,而不是引用,那麼不能改動函數返回值,因此上面的operator[]返回應是引用,那麼:
void testFunc(TextBlock& tb)
{
    tb[0] = 'x'; //如果operator[]返回的不是引用,那麼此處編譯出錯
}
 
 
(3)如果想在const成員函數中修改成員變量,那麼在成員變量前使用mutable修飾
mutable int pos;
 
(4)在const和non-const成員函數中避免重複
 
 
 
 
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章