让我们说我有一个
class Dictionary
{
vector<string> words;
void addWord(string word)//adds to words
{
/...
}
bool contains(string word)//only reads from words
{
//...
}
}
有没有办法让编译器检查包含isnt更改单词vector。 Ofc这只是一个类数据成员的例子,我希望它能与任意数量的数据成员一起使用。 附:我知道我没有公开:私有:我故意把它留下来让代码更短,问题更清晰。
答案 0 :(得分: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 :(得分: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");
}
答案 2 :(得分:2)
通常将方法声明为“const”可实现此目的:
bool contains(string word) const
// ...
编译器会告诉您是否在类成员上使用的任何方法也不是const。另请注意,您可以通过引用传递字符串以避免复制(创建word
参数std::string const&
)。
答案 3 :(得分:2)
将您的函数声明为const:
void addWord(string word) const
{
/...
}
如果您尝试更改正文中的任何成员,编译器将给出错误。 另请注意,在声明为const的方法中,您不能调用其他未声明为const的方法。
答案 4 :(得分:1)
使成员函数const:
bool contains(string word) const
{
//...
}