Const 关键字附加到函数定义的末尾...它有什么作用?
假设我在 C++ 中定义一个函数如下:
void foo(int &x) const {
x = x+10;
}
假设我按如下方式调用它:
int x = 5;
foo(x);
现在通常(没有 const
关键字),这将成功地将 x
的值从由于变量是通过引用传递的,因此从调用者的角度来看。 const
关键字会改变这一点吗? (即从调用者的角度来看,x
的值现在是 15?)
我想我对 const
关键字附加到末尾时的作用感到困惑函数定义的...任何帮助表示赞赏。
Suppose I define a function in C++ as follows:
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. Does the const
keyword change this? (i.e. From the caller's perspective, is the value of x
now 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这行不通。您只能对成员函数进行 const 限定,而不能对普通的非成员函数进行 const 限定。
对于成员函数,这意味着隐式
this
参数是 const 限定的,因此您不能调用任何非 const 限定的成员函数或修改类实例的任何非可变数据成员调用成员函数的位置。This won't work. You can only const-qualify a member function, not an ordinary nonmember function.
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.