gpt4 book ai didi

c++ - 函数定义末尾的 "const"是什么意思(在上下文中)?

转载 作者:IT老高 更新时间:2023-10-28 21:50:46 29 4
gpt4 key购买 nike

Possible Duplicate:
What is the meaning of a const at end of a member function?

如果我的类定义如下:

type CLASS::FUNCTION(int, const char*) const

右括号后面的最后一个 const 是什么意思,如何将它应用到函数中:

type CLASS::FUNCTION(int var1, const char* var2) {

}

最佳答案

表示该函数不会修改对象的可观察状态。

在编译器术语中,这意味着您不能在 const 对象(或 const 引用或 const 指针)上调用函数,除非该函数也被声明为 const .此外,声明为 const 的方法不允许调用未声明的方法。

更新: 正如 Aasmund 完全正确添加的那样,const 方法可以更改声明为 mutable 的成员的值。

例如,有一个只读操作(例如 int CalculateSomeValue() const)会缓存其结果,因为调用成本很高。在这种情况下,您需要有一个 mutable 成员来将缓存的结果写入。

我为遗漏道歉,我试图快速且切中要害。 :)

关于c++ - 函数定义末尾的 "const"是什么意思(在上下文中)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5200572/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com