函式宣告末尾的"const"表示什麼?
classFoo{public:intBar(int random_arg)const{// code}};
小結:Bar(int )函式宣告末尾帶有const,表示不允許Bar(int)函式對類Foo中的成員進行修改(mutable成員除外)。
const
after
a function declaration means that the function is not allowed to change any class members (except ones that are marked mutable
).
So this use of const only makes sense, and is hence only allowed, for member functions.
To illustrate a bit more what's going on internally (based on a comment of ereOn above): Declaring a member method results in a function declaration that takes a member pointer as a first parameter. So a method int
Foo::Bar(int random_arg)
(without the const at the end) results in a function like this int
Foo_Bar(Foo* this, int random_arg)
Foo
f; f.Bar(4);
will result in 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)
.
const
before
an argument in a function definition
const
for
a variable: that the value is not allowed to change in the function body. (I highlighted the word definition here, since the same const keyword in the function declaration will
not change the function type signature; see for instance this answer for an more detailed explanation.)
Note that const
is
a highly overloaded operator and the syntax is often not straightforward in combination with pointers. Some readings about const correctness and the const keyword: