函数声明末尾的"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
    }
};
小结: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 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:

Const correctness

The C++ 'const' Declaration: Why & How


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值