为什么引用成员可以通过const成员函数进行修改? [英] Why can reference members be modified by const member functions?
问题描述
即使const成员函数将修改成员的值,也将编译.怎么会这样?
The following will compile even though a const member function will modify the value of a member. How so ?
#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;
}
推荐答案
类成员函数的 const
限定词表示该成员函数(例如, foo :: operator()const
)不能从客户端的角度来看更改对象的状态(即,它是抽象状态).这与说对象的原始位不会改变的说法完全不同.
The const
qualifier of a class member function indicates that this member function (e.g., foo::operator() const
) cannot change the state of the object from the client's point of view (i.e., it's abstract state). This is not exactly the same as saying that the object's raw bits are not going to change.
除非对象可以解决别名问题.在您的情况下,编译器不能.这是由于存在非恒定别名(即 std :: string& str
),因此对象的状态是可修改的.
It is forbitten to C++ compilers to consider objects as raw bits, unless they can resolve the problem of aliasing. which in your case the compiler cannot. This is due to the fact that a non-constant alias exists (i.e., std::string &str
) and consequently the state of the object is modifiable.
也就是说,在对象 a
上调用 operator()
不会更改 a
的状态(即,尽管 ext
已更改, str
仍然是 ext
的别名.)
That is, calling operator()
on object a
does not change the state of a
(i.e., although ext
has changed, the str
still remains an alias of ext
).
上面的内容也解释了为什么用指向常量的指针(即 std :: string * const str
)指向对象不能保证不会修改该对象.它仅保证该对象不会通过该指针更改.
The above also explains why pointing at an object with a pointer to constant (i.e., std::string * const str
) does not guarantee that the object won't be modified. It only guarantees that the object won't change through that pointer.
这篇关于为什么引用成员可以通过const成员函数进行修改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!