[英]Is there a way in c++ to make sure that class member function isnt changing any of the class data members?
可以说我有一个
class Dictionary
{
vector<string> words;
void addWord(string word)//adds to words
{
/...
}
bool contains(string word)//only reads from words
{
//...
}
}
有没有办法让编译器检查包含不改变的单词向量。 Ofc 这只是一个 class 数据成员的示例,我希望它可以与任意数量的数据成员一起使用。 PS 我知道我没有 public: 和 private:,我故意将其省略以使代码更短且问题更清晰。
如果您希望编译器强制执行此操作,请声明成员 function const
:
bool contains(string word) const
{
...
}
一个const
function 不允许修改其成员变量,只能调用其他const
成员函数(无论是自己的,还是其成员变量的)。
此规则的例外是成员变量被声明为mutable
。 [但mutable
不应用作通用的const
解决方法; 它仅适用于 object 的“可观察” state 应该是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
}
};
将它们标记为const
:
bool contains(string word) const
// ^^^^^^
另一件好事:您只能调用其他const
成员函数:) 还有一件好事:您可以在 class 的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");
}
通常将方法声明为“const”可以实现这一点:
bool contains(string word) const
// ...
编译器会告诉您是否在 class 成员上使用了任何不是 const 的方法。 另请注意,您可以通过引用传递字符串以避免复制(使word
参数std::string const&
)。
将您的 function 声明为 const:
void addWord(string word) const { /... }
如果您尝试更改正文中的任何成员,编译器将给出错误。 另请注意,在声明为 const 的方法内,您不能调用未声明为 const 的其他方法。
使成员 function 为常量:
bool contains(string word) const
{
//...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.