函数/方法签名后面的 const 是什么意思?
根据 MSDN 的说法:“当遵循成员函数的参数列表时,const 关键字指定该函数不会修改调用它的对象。”
有人可以澄清一下吗?这是否意味着该函数不能修改对象的任何成员?
bool AnalogClockPlugin::isInitialized() const
{
return initialized;
}
According to MSDN: "When following a member function's parameter list, the const keyword specifies that the function does not modify the object for which it is invoked."
Could someone clarify this a bit? Does it mean that the function cannot modify any of the object's members?
bool AnalogClockPlugin::isInitialized() const
{
return initialized;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这意味着该方法不会修改成员变量(声明为可变的成员除外),因此可以在类的常量实例上调用它。
It means that the method do not modify member variables (except for the members declared as
mutable
), so it can be called on constant instances of the class.另请注意,虽然成员函数无法修改未标记为可变的成员变量,但如果成员变量是指针,则成员函数可能无法修改指针值(即指针指向的地址),但它可以修改指针指向的内容(实际的内存区域)。
例如:
Note also, that while the member function cannot modify member variables not marked as mutable, if the member variables are pointers, the member function may not be able to modify the pointer value (i.e. the address to which the pointer points to), but it can modify what the pointer points to (the actual memory region).
So for example:
编译器不允许 const 成员函数更改 *this 或
为此对象调用非常量成员函数
The compiler won’t allow a const member function to change *this or to
invoke a non-const member function for this object
正如 @delroth 所回答的,这意味着成员函数不会修改任何成员变量,除了声明为可变的变量之外。您可以在此处查看有关 C++ 中 const 正确性的常见问题解答
As answered by @delroth it means that the member function doesn't modify any memeber variable except those declared as mutable. You can see a good FAQ about const correctness in C++ here