“const”是什么意思。在函数声明结束时? [英] What is meant with "const" at end of function declaration?

查看:164
本文介绍了“const”是什么意思。在函数声明结束时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

const的含义最后在C ++方法声明中?

书,其中有如下的书写:

Hi I got a book, where there is written something like:

class Foo 
{
public:
    int Bar(int random_arg) const
    {
        // code
    }
};

此外,一个旁白的问题:为什么应该/应该不使用 const 之前的参数声明?

Also, a by-the-way question: why should/shouldn't I use const before argument declarations? What does that change ?

int Foo (const int Bar) { /* code */ }

编辑:
所以,如果我现在做:

So if I do now:

Foo v1, v2;

(const标记的)Bar函数在内存中存在3次或1次?

Will the (const-tagged) Bar function exist 3 times or 1 time in memory?

推荐答案

const 后,函数声明意味着该函数不允许更改任何类成员(标记为 mutable 的成员除外)。所以这个使用const只有有意义,因此只允许,对于成员函数。

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.

为了更好地说明内部发生了什么(基于ereOn上面):声明一个成员方法导致一个函数声明,它接受一个隐式的this指针作为第一个参数。所以一个方法 int Foo :: Bar(int random_arg)(没有const结束)导致一个函数 int Foo_Bar ,int random_arg)和一个调用如 Foo f; f.Bar(4)将在内部对应于 Foo f; Foo_Bar(& f,4)。现在在末尾添加const( int Foo :: Bar(int random_arg)const )可以理解为一个带有const指针的声明: int Foo_Bar(const Foo * this,int random_arg)。在函数定义中的参数之前的

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 an implicit this 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 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).

const 作为变量的 const :该值不允许在函数体中更改。 (我在这里突出显示了定义,因为函数声明中的相同的const关键字不会改变函数类型签名;参见例如这个回答更详细的解释。)

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.)

注意 const 是一个高度重载的限定符,并且语法通常不直接与指针组合。关于const正确性和const关键字的一些读数:

Note that const is a highly overloaded qualifier and the syntax is often not straightforward in combination with pointers. Some readings about const correctness and the const keyword:

Const正确性

C ++const声明: 如何

这篇关于“const”是什么意思。在函数声明结束时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆