http://stackoverflow.com/questions/3141087/what-is-meant-with-const-at-end-of-function-declaration
class Foo
{
public:
int Bar(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)
, and a call like 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 as in your example means the same as 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:
The C++ 'const' Declaration: Why & How