常数函数
我发现了一个函数原型如下:
const ClassA* ClassB::get_value() const
上面的语句意味着什么?我可以更改ClassA对象的成员吗?
Possible Duplicates:
What is the meaning of a const at end of a member function?
about const member function
I found one function prototype as under:
const ClassA* ClassB::get_value() const
What does the above statement signify? Can I change the member of ClassA object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
第一个 const 意味着它返回的是指向 const A 的指针。所以不,你不能改变它返回的内容(除非你放弃 const 性,如果它返回的对象实际上定义为 < ,这将给出未定义的行为code>const,而不是返回一个指向本身未定义为
const
的对象的const
指针)。第二个 const 意味着
get_value
无法更改调用它的ClassB
的任何(不可变)状态(除其他外,它是传递性的,因此< code>ClassB::get_value 只能调用其他也是 const 限定的成员函数)。The first const means what it returns is a pointer to const A. So no, you can't change what it returns (unless you cast away the const-ness, which will give undefined behavior if the object it returns is actually defined as
const
, rather than returning aconst
pointer to an object that itself wasn't defined asconst
).The second const means that
get_value
can't change any of the (non-mutable) state of theClassB
on which it's invoked (among other things, it's transitive, soClassB::get_value
can only call other member functions that are alsoconst
-qualified).不会。
该函数返回的 ClassA 指针标记为
const
。这意味着您不应更改其任何值。更改值并非不可能,因为有多种方法可以绕过
const
标记,但您显然不打算改变它。No.
The ClassA pointer returned by that function is marked
const
. That means that you should not change any of its values.It won't be impossible to change the values because there are various ways to get around a
const
marking, but you are clearly not meant to be changing it.get_value
是ClassB
的 const 成员函数,因此它不能修改其定义内的ClassB
的任何非可变数据成员。但它可以修改ClassA
的成员,例如以下编译(泄漏内存,但这在这里并不重要)
get_value
is a const member function ofClassB
so it cannot modify any non-mutable data members ofClassB
inside its definition. But it can however modify members ofClassA
For example the following compiles (leaks memory but that is not much of a concern here)
get_value()
是一个只读函数,不会修改为其调用的ClassB
对象。它返回一个指向ClassA
对象的只读指针。您可以通过使用const_cast
放弃其常量来修改该对象所指向的对象。但理想的做法是复制这个对象并改变它。get_value()
is a read-only function that does not modify theClassB
object for which it is called. It returns a read-only pointer to aClassA
object. You can modify the object pointed to by this object by casting away its constness usingconst_cast
. But the ideal thing to do is to make a copy of this object and mutate that.