请教一个non-const member function的有关问题
请问一个non-const member function的问题?
请问下:
Test test;
test[0] = 1 ;
但是如果隐去:
char& operator[](int index)程序会报错:
我想问的是:为什么 non-const成员函数不存在的时候,test[0] = 1 直接调用const成员函数
请问下,non-const和const是根据什么规则来调用函数,这是什么原理呀?
------解决方案--------------------
C++ 编程语言里面的话:对于const和非const对象都可以调用const成员函数,而非const成员函数则只能对非const调用。
如果你去掉non-const函数的话,你的程序就变成了修改index的那个char值了。肯定会出错的。const就是用来表示不允许在其函数范围内修改值。
------解决方案--------------------
非const可以调用const,但const只能调用const。
- C/C++ code
class Test { public: Test(void); ~Test(void); private: char a[100]; public: const char& operator[](int index) const { printf("111"); return a[index]; } char& operator[](int index) { printf("222"); return a[index]; } };
请问下:
Test test;
test[0] = 1 ;
但是如果隐去:
char& operator[](int index)程序会报错:
我想问的是:为什么 non-const成员函数不存在的时候,test[0] = 1 直接调用const成员函数
请问下,non-const和const是根据什么规则来调用函数,这是什么原理呀?
------解决方案--------------------
C++ 编程语言里面的话:对于const和非const对象都可以调用const成员函数,而非const成员函数则只能对非const调用。
如果你去掉non-const函数的话,你的程序就变成了修改index的那个char值了。肯定会出错的。const就是用来表示不允许在其函数范围内修改值。
------解决方案--------------------
非const可以调用const,但const只能调用const。