2011-06-02 93 views
3

比方說,我有一個在C++中有沒有辦法確保類成員函數不會更改任何類數據成員?

class Dictionary 
{ 
vector<string> words; 
void addWord(string word)//adds to words 
{ 
/... 
} 
bool contains(string word)//only reads from words 
{ 
//... 
} 
} 

有沒有一種方法,使編譯器檢查包含心不是改變的話載體。 Ofc這只是一個類數據成員的例子,我希望它能與任何數量的數據成員一起工作。 P.S.我知道我沒有公開:私人:我故意忽略它,使代碼更短,問題更清楚。

回答

16

如果你希望編譯執行這一點,那麼宣佈該成員函數const

bool contains(string word) const 
{ 
    ... 
} 

const功能不允許莫不同的是它的成員變量,並且只能調用其他const成員函數(它自己或成員變量的成員函數)。

此規則的例外是成員變量聲明爲mutable[但不應將mutable用作通用const解決方法;它才真正意味着當物件的情況的「觀察的」狀態應該是const,但內部實現(如引用計數或懶惰的評價)仍然需要改變。]也

注意const不通過例如傳播指針。

因此,在總結:

class Thingy 
{ 
public: 
    void apple() const; 
    void banana(); 
}; 

class Blah 
{ 
private: 
    Thingy t; 
    int *p; 
    mutable int a; 

public: 
    Blah() { p = new int; *p = 5; } 
    ~Blah() { delete p; } 

    void bar() const {} 
    void baz() {} 

    void foo() const 
    { 
     p = new int; // INVALID: p is const in this context 
     *p = 10;  // VALID: *p isn't const 

     baz();  // INVALID: baz() is not declared const 
     bar();  // VALID: bar() is declared const 

     t.banana(); // INVALID: Thingy::banana() is not declared const 
     t.apple(); // VALID: Thingy::apple() is declared const 

     a = 42;  // VALID: a is declared mutable 
    } 
}; 
+1

+1爲指針的東西,因爲'const'只適用於頂層(即不能改變指針本身,只能指向對象)。 – Xeo 2011-06-02 10:36:49

+1

像Xeo說非常酷的示例與ponters ... + 1 ofc :) – NoSenseEtAl 2011-06-02 10:44:14

+1

其實你應該提到關於可變關鍵字 – 2011-06-02 10:52:03

2

通常聲明方法「常量」實現這一點:

bool contains(string word) const 
// ... 

編譯器會告訴你,如果你使用任何避孕方法的類成員,是不是也是常量。還要注意,您可以通過引用傳遞字符串以避免複製(使word參數std::string const&)。

6

將其標記爲const

bool contains(string word) const 
//      ^^^^^^ 

另一個積極的東西:你只能調用其他const成員函數! :) 另一個好東西:你不準叫上你的課,例如const對象的功能:

void foo(const Dictionary& dict){ 
    // 'dict' is constant, can't be changed, can only call 'const' member functions 
    if(dict.contains("hi")){ 
    // ... 
    } 
    // this will make the compiler error out: 
    dict.addWord("oops"); 
} 
+1

哇,cpp很棒(儘管我知道const,我從來沒有理解它超出了不可修改的變量)。tnx – NoSenseEtAl 2011-06-02 10:41:51

1

使成員函數常量:

bool contains(string word) const 
{ 
//... 
} 
2

聲明你的函數爲const:

void addWord(string word) const { /... }

如果試圖改變身體內的任何成員,編譯器會給出一個錯誤。 另請注意,在聲明爲const的方法內部,不能調用其他未聲明爲const的方法。