C++ - const 这里代表什么?
如果我得到如下 C++ 语句:
double getPrice() const;
这里 const
代表什么?
谢谢。
If I get a C++ statement as follows:
double getPrice() const;
What doesn const
represent here?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这适用于成员函数(在类或结构中)。这意味着该方法不会更改它所操作的实例的状态(例如,不会更改任何成员变量)。
This is for member functions (in classes or structs). It means that the method won't change the state of the instance it operates on (won't change any member variables for example).
当您调用非静态成员函数时,您总是在某个对象上调用它,对吧?该对象作为参数(隐式)传递。例如,如果 GetPrice 是类 X 的方法,则它有一个
X&
类型的隐式参数。那么该方法是 const,隐式参数的类型是 const X&,因此成员函数不能更改调用它的对象的任何数据成员,除非该数据成员已声明可变的
。When you call nonstatic member functions, you always call it on some object, right? That object is passed (implicitly) as a parameter. For example, if GetPrice is the method of class X, then it has an implicit parameter of type
X&
. Then the method is const, the implicit argument is of typeconst X
&, therefore the member function cannot change any data member of the object on which it was invoked, UNLESS the data member was declaredmutable
.它表示它不会作为副作用而改变类的成员。
It signifies that it will not change the members of the class as a side effect.
const
表示getPrice()
不会修改实例字段,除非那些显式声明为mutable
的字段。const
means thatgetPrice()
won't modify instance fields, except those explicitly declared asmutable
.