2011-06-02 34 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的方法。