# 函数声明末尾的"const"表示什么？

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
}
};

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 constfor 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:

10-29 489

08-01 4.8万

10-12 1085

11-01 2738

10-18 128

09-07 431

05-12 3107

08-25 6254

06-08 4500

08-01 1690

• 写评论