C++ 方法允许使用 const
限定符来指示该方法不更改对象。但是,这是什么意思?例如。如果实例变量是指针,这是否意味着指针没有改变,或者它们指向的内存没有改变?
具体来说,这是一个最小的示例类
class myclass {
int * data;
myclass() {
data = new int[10];
}
~myclass() {
delete [] data;
}
void set(const int index) const {
data[index] = 1;
}
};
方法 set
是否正确符合 const
的条件?它不会改变成员变量 data
,但它确实会改变数组的内容。
原文由 Daniel 发布,翻译遵循 CC BY-SA 4.0 许可协议
最简洁,这意味着
this
的类型是const T *
在 const 成员函数中,其中T *
T
是你的类,而在非限定函数中它是---
。您的方法
set
不会改变data
,因此可以将其限定为 const。换句话说,myclass::data
被访问为this->data
并且是int * const
类型。