关于网友提出的“ C++const修饰的函数问题”问题疑问,本网通过在网上对“ C++const修饰的函数问题”有关的相关答案进行了整理,供用户进行参考,详细问题解答如下:
问题: C++const修饰的函数问题
描述: 为什么Array& operator[] (const int& index) const改为Array& operator[] (const int& index)就编译通过,而Array operator[] (const int& index)const用const来修饰,编译时却不会出问题?? 求高手指教
编译出错提示:
error C2440: 'return' : cannot convert from 'const struct Array' to 'struct Array &'
#include
using namespace std;
struct Array
{
int a;
};
class OpeArr
{
public:
Array arr[10];
public:
OpeArr()
{
for (int i = 0; i < 10; i++)
{
arr[i].a = i;
}
}
Array operator[] (const int& index)const
{
return arr[index];
}
Array& operator[] (const int& index) const
{
return arr[index];
}
};
int main()
{
OpeArr test;
cout << test.arr[2].a << endl;
return 0;
}
解决方案1: const 函数的基本含义就是不能修改 this 里面成员的值.
Array& operator[] (const int& index) const 返回一个引用, 外面不是随便修改了?
得 const Array& operator[] (const int& index) const 才行.
Array operator[] (const int& index)const 返回的是一个拷贝, 外面修改的也是拷贝的对象, 不会修改到对象的值, 所以没问题.
以上介绍了“ C++const修饰的函数问题”的问题解答,希望对有需要的网友有所帮助。
本文网址链接:http://www.codes51.com/itwd/3709589.html