我在 c++ 代码的这一部分中找不到第二个常量实用程序,有人可以解释一下吗?
I can't find the utility of the second const in this part of c++ code, can someone explain please?
表示成员函数中的this
指针为const
。换句话说,调用不会修改对象。(它返回的任何引用/指针也将是const
)。
这种语法适用于类内部的方法。标记为const
(代码中的第二个const
)的方法不能修改对象的属性,只能读取。如果将对象实例化为const
, Const方法是唯一可调用的方法。情况:
class A {
public:
void put(int v) {
var = v;
}
int read() const {
return var;
}
private:
int var;
}
int main() {
A obj;
obj.put(3);
const A obj2 = obj;
obj2.read(); // OK, returns 3;
obj2.put(4); // Compile time error!
}
Michael的回答几乎涵盖了所有内容,但还有其他一些方面:
- 只允许在const方法中调用const方法。
- 可以更改成员,如果你声明他们为可变的。
- 您将无法更改类的任何其他成员。
只有成员函数可以const限定,非成员函数不能。对于 c++ 也是如此。C没有成员函数的概念,因此它们不能。
相关文章:
- 有人能解释一下为什么下界是这样工作的吗C++的
- 我是c ++的新手,你能解释一下在这种情况下的指针吗
- 有人能为我解释一下C++代码吗
- 你能解释一下什么运行时错误是如何解决它的吗?
- 有人可以解释一下这段代码如何能够反转字符串
- 解释一下 for (char c : str) 的作用?
- 有人可以解释一下这个矩阵幂函数是如何工作的吗?
- 有人可以向我解释一下这段代码的作用吗?
- 任何人都可以解释一下我是否需要 & 在第一个代码片段中
- 我不完全确定此代码的行为.有人可以向我解释一下吗?
- 有人可以解释一下吗?这是关于数组和数组内部 if 语句的一些处理
- 我无法理解这一点,有人可以帮我解释一下吗?
- 有人可以解释一下复制功能的作用吗?
- 解释一下这个排序算法是如何工作的?
- 我在 2D 数组的动态内存分配中遇到了一些奇怪的代码C++? 请解释一下这是什么?
- 有人能给我解释一下下面的模板代码吗
- 有人能解释一下这些说法背后的逻辑是什么吗
- 在给定的代码中,有人可以解释一下(int i = 0; i<len; i++)count[str[i]]++的代码片段;
- 谁能解释一下这个BFS代码是如何工作的?
- 有人可以解释一下'sizeof'在此代码中返回的结果吗