我可以毫无问题地运行以下代码。我注意到main中的a.bytes和byte都更改为“ B”。那么A的get()函数中的“ const”是做什么的呢?如下更改从A获得的字节会不会有问题?
注意:我不在乎A的值是否会改变。我只是想知道我是否会遇到无法预料的问题,尤其是当我在解构函数中释放A时,无论我对main的字节采取何种疯狂操作。
class A{
public:
A(){
bytes = (char *)malloc(12);
bytes[0] = 'A';
bytes[1] = 0;
}
~A(){
free(bytes);
}
char * get() const{
return bytes;
}
char * bytes;
};
int _tmain(int argc, _TCHAR* argv[])
{
A a;
char * bytes = a.get();
bytes[0] = 'B';
return 0;
}
这仅表示成员函数将不会(也不能)修改对象内部的任何内部数据。
它还会导致this
成员函数内部的变量为const
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句