简体   繁体   English

在函数定义的末尾附加了const关键字……它有什么作用?

[英]Const keyword appended to the end of a function definition… what does it do?

Suppose I define a function in C++ as follows: 假设我在C ++中定义一个函数,如下所示:

void foo(int &x) const {
  x = x+10;
}

And suppose I call it as follows: 假设我这样称呼它:

int x = 5;
foo(x);

Now typically (without the const keyword), this would successfully change the value of x from the caller's perspective since the variable is passed by reference. 现在,通常(没有const关键字),由于变量是通过引用传递的,因此从调用者的角度来看,这将成功更改x的值。 Does the const keyword change this? const关键字会改变吗? (ie From the caller's perspective, is the value of x now 15?) (即从调用者的角度来看, x的值现在是15吗?)

I guess I'm confused as to what the const keyword does when it is appended to the end of a function definition... any help is appreciated. 我猜想当const关键字附加到函数定义的末尾时会做什么,对此我感到困惑……任何帮助都是值得的。

This won't work. 这行不通。 You can only const-qualify a member function , not an ordinary nonmember function. 您只能const限定成员函数 ,而不是普通的非成员函数。

For a member function, it means that the implicit this parameter is const-qualified, so you can't call any non-const-qualified member functions or modify any non-mutable data members of the class instance on which the member function was called. 对于成员函数,这意味着隐式的this参数是const限定的,因此您不能调用任何非const限定的成员函数,也不能修改调用了该成员函数的类实例的任何非可变数据成员。 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM