当函数后面的“const”关键字有什么作用?
Possible Duplicate:
What is the meaning of a const at end of a member function?
I have seen some classes that have something like this.
void something() const;
What does const
means?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
除了 SRM 所说的(该函数不能更改类的任何成员(这并不完全正确,例如在
mutable
成员的情况下,它仍然可以更改)),这意味着您可以对const
的事物调用此成员函数。所以如果你得到一个Foo const& foo
作为参数,您只能调用像问题中那样声明为const
的成员。In addition to what SRM said (that the function cannot alter any members of the class (which is not exactly true, e.g. in the case of
mutable
members, which still can be altered)), it means that you can call this member function on things that areconst
. So if you get aFoo const& foo
as a parameter, you can only call members that are declaredconst
like in your question.这意味着
某物
不能修改类的成员变量。该规则的例外情况是,如果存在使用
mutable
关键字声明的成员变量。例如,假设您有一个
std::map< int, int > var
成员变量和执行以下操作的方法:如果 42 不在容器中,则不会编译,因为
var[42]
会修改var
。将var
声明为mutable
可以让您通过编译。It means that
something
may not modify member variables of the class.The exception to the rule is if there are member variables declared with the
mutable
keyword.For example, suppose you have a
std::map< int, int > var
member variable and a method that does the following:That will not compile since
var[42]
modifiesvar
if 42 is not in the container. Declaringvar
asmutable
allows you to pass compilation.这意味着该函数不会修改任何成员变量。更准确地说,这意味着该函数不能更改该类的任何非静态或不可变成员变量
It means the function will not modify any member variables. To be more precise, it means the function cannot alter any non-static or immutable member variables of that class
绝对准确地说,它使函数中的隐式 this 指针成为指向 const 对象的指针。
来自9.2.1“this指针”
所有其他行为(您不能修改对象成员、您可以使用 const 对象调用函数等)都源于此。
To be absolutely precise - it makes the implicit
this
pointer in the function a pointer to aconst
object.From 9.2.1 "The this pointer""
All the other behaviors (that you can't modify the object members, that you can call the function using a
const
object, etc) fall from that.它声明该函数不能更改任何数据。使其成为只读函数。
it declares that this function can not change any data. Makes it a Read Only Function.