【发布时间】:2014-05-02 20:57:28
【问题描述】:
以下内容将compile,即使 const 成员函数会修改成员的值。怎么会?
#include <iostream>
struct foo
{
std::string &str;
foo(std::string &other) : str(other) {}
void operator()(std::string &some) const
{
str += some;
}
};
int main()
{
std::string ext("Hello");
foo a{ ext };
std::string more(" world!");
a(more);
cout << a.str;
return 0;
}
【问题讨论】:
-
修改成员所指的内容,不修改成员。
-
因为它不会修改引用本身。应用
+=运算符后,引用没有改变,只有内部字符串内容会改变(在字符串的上下文中,this仍然相同)。 -
用 std::string* 代替 & 试试,你会看到同样的结果。
-
它被称为按位
const,这是 C++ 强制执行的,而不是逻辑const。见this question 和this one。
标签: c++