在c ++中是否有一种方法可以确保类成员函数不会更改任何类数据成员?

NoS*_*tAl 3 c++ syntax

让我们说我有一个

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

有没有办法使编译器检查包含不更改单词向量.Ofc这只是一个类数据成员的例子,我希望它能与任意数量的数据成员一起使用.PS我知道我没有公开:私有:我故意把它留下来让代码更短,问题更清晰.

Oli*_*rth 16

如果您希望编译器强制执行此操作,则声明成员函数const:

bool contains(string word) const
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

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
    }
};
Run Code Online (Sandbox Code Playgroud)


Xeo*_*Xeo 6

标记为const:

bool contains(string word) const
//                        ^^^^^^
Run Code Online (Sandbox Code Playgroud)

另一个积极的事情:你只能调用其他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");
}
Run Code Online (Sandbox Code Playgroud)