“const”是什么?函数定义末尾的意思(在上下文中)?
可能的重复:
a 的含义是什么const 位于成员函数末尾?
如果我的类定义如下:
type CLASS::FUNCTION(int, const char*) const
右括号后的最后一个 const 是什么意思,以及如何将其应用于函数:
type CLASS::FUNCTION(int var1, const char* var2) {
}
Possible Duplicate:
What is the meaning of a const at end of a member function?
If my class definition is as follows:
type CLASS::FUNCTION(int, const char*) const
What does the last const after the closing bracket mean, and how do I apply it to the function:
type CLASS::FUNCTION(int var1, const char* var2) {
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这意味着该函数不会修改对象的可观察状态。
用编译器术语来说,这意味着您不能在 const 对象(或 const 引用或 const 指针)上调用函数,除非该函数也被声明为 const。此外,声明为 const 的方法不允许调用非 const 的方法。
更新: 正如 Aasmund 完全正确地补充的那样,
const
方法可以更改声明为mutable
的成员的值。例如,使用一个只读操作(例如 intCalculateSomeValue() const)来缓存其结果可能是有意义的,因为调用它的成本很高。在这种情况下,您需要有一个
mutable
成员来写入缓存的结果。我为我的疏忽表示歉意,我试图说得快点、切中要害。 :)
It means that this function does not modify the observable state of an object.
In compiler terms, it means that you cannot call a function on a
const
object (or const reference or const pointer) unless that function is also declared to beconst
. Also, methods which are declaredconst
are not allowed to call methods which are not.Update: as Aasmund totally correctly adds,
const
methods are allowed to change the value of members declared to bemutable
.For example, it might make sense to have a read-only operation (e.g.
int CalculateSomeValue() const
) which caches its results because it's expensive to call. In this case, you need to have amutable
member to write the cached results to.I apologize for the omission, I was trying to be fast and to the point. :)
函数末尾的
const
意味着它不会修改调用它的对象的状态(即this
)。您还需要在方法定义末尾提及关键字
const
。另请注意,只有成员函数的末尾才能包含此非修饰符关键字const
。const
at the end of the function means it isn't going to modify the state of the object it is called up on ( i.e.,this
).You need to mention the keyword
const
at the end of the method definition too. Also note that only member functions can have this non-modifier keywordconst
at their end.意味着这个函数不会修改任何成员变量,或者调用任何非常量成员函数。
如果您有一个指向类实例的 const 引用/指针,您将只能调用像这样标记为 const 的函数。
Means that this function will not modify any member variables, or call any non-const member functions.
If you have a const reference/pointer to an instance of the class, you will only be able to call functions that are marked
const
like this.这意味着该方法是 const,并且意味着该方法不会修改任何成员,因此可以在对象是 const 的设置中使用。
This means the method is const, and means the method will not modify any members, it can thus be used in a setting where the object is const.
检查(即读取)而不是修改或写入对象的成员函数。以下链接对我有帮助。
http://www.parashift.com/c++-faq -lite/const- Correctness.html#faq-18.10
A member function that inspects, i.e. reads, rather than modifies or writes to an object. The following link is helpful to me.
http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.10