What is the meaning of a const at end of a member function?(成员函数末尾的 const 是什么意思?)
问题描述
C++ 中的 const
关键字写在成员函数的末尾(参数列表之后)究竟是什么意思?
What exactly does the const
keyword in C++ mean when it's written at the end of a member function (after the argument list)?
推荐答案
这意味着 *this
是该成员函数内部的 const
,即它不会改变对象.
It means that *this
is const
inside that member function, i.e. it doesn't alter the object.
关键字this
是prvalue 表达式,其值是调用函数的对象的地址.X
类的成员函数中this
的类型是X*
.如果成员函数声明为const
,则this
的类型为const X*
.[第 9.3.2 节 §1]
The keyword
this
is a prvalue expression whose value is the address of the object for which the function is called. The type ofthis
in a member function of a classX
isX*
. If the member function is declaredconst
, the type ofthis
isconst X*
. [section 9.3.2 §1]
在一个const
成员函数中,调用该函数的对象是通过一个const
访问路径访问的;因此,const
成员函数不得修改对象及其非静态数据成员.[第 9.3.2 节 §2]
In a const
member function, the object for which the function is called is accessed through a const
access path; therefore, a const
member function shall not modify the object and its non-static data members. [section 9.3.2 §2]
这意味着可以在类的 const
实例上调用 const
成员函数.不能在 [1]const
对象上调用非 const
成员函数,因为它可能会尝试修改它.
This means that a const
member function can be called on a const
instance of the class. A non-const
member function can't be called on [1]a const
object, since it could potentially try to modify it.
<支持>[1] 注意:临时不是 const
对象,除非它是 const
类型.
[1] Note: a temporary is not a const
object unless it's of const
type.
这篇关于成员函数末尾的 const 是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:成员函数末尾的 const 是什么意思?


基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05