What is meant with quot;constquot; at end of function declaration?(“const是什么意思?在函数声明的末尾?)
问题描述
I got a book, where there is written something like:
class Foo
{
public:
int Bar(int random_arg) const
{
// code
}
};
What does it mean?
A "const function", denoted with the keyword const
after a function declaration, makes it a compiler error for this class function to change a member variable of the class. However, reading of a class variables is okay inside of the function, but writing inside of this function will generate a compiler error.
Another way of thinking about such "const function" is by viewing a class function as a normal function taking an implicit this
pointer. So a method int Foo::Bar(int random_arg)
(without the const at the end) results in a function like int Foo_Bar(Foo* this, int random_arg)
, and a call such as Foo f; f.Bar(4)
will internally correspond to something like Foo f; Foo_Bar(&f, 4)
. Now adding the const at the end (int Foo::Bar(int random_arg) const
) can then be understood as a declaration with a const this pointer: int Foo_Bar(const Foo* this, int random_arg)
. Since the type of this
in such case is const, no modifications of member variables are possible.
It is possible to loosen the "const function" restriction of not allowing the function to write to any variable of a class. To allow some of the variables to be writable even when the function is marked as a "const function", these class variables are marked with the keyword mutable
. Thus, if a class variable is marked as mutable, and a "const function" writes to this variable then the code will compile cleanly and the variable is possible to change. (C++11)
As usual when dealing with the const
keyword, changing the location of the const key word in a C++ statement has entirely different meanings. The above usage of const
only applies when adding const
to the end of the function declaration after the parenthesis.
const
is a highly overused qualifier in C++: the syntax and ordering is often not straightforward in combination with pointers. Some readings about const
correctness and the const
keyword:
Const correctness
The C++ 'const' Declaration: Why & How
这篇关于“const"是什么意思?在函数声明的末尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:“const"是什么意思?在函数声明的末尾?
基础教程推荐
- C语言 structural body结构体详解用法 2022-12-06
- 如何C++使用模板特化功能 2023-03-05
- C++使用easyX库实现三星环绕效果流程详解 2023-06-26
- C++详细实现完整图书管理功能 2023-04-04
- C/C++编程中const的使用详解 2023-03-26
- C++中的atoi 函数简介 2023-01-05
- C利用语言实现数据结构之队列 2022-11-22
- 一文带你了解C++中的字符替换方法 2023-07-20
- C语言基础全局变量与局部变量教程详解 2022-12-31
- 详解c# Emit技术 2023-03-25