【发布时间】:2015-10-21 00:01:15
【问题描述】:
看看这个简单的数组类
class Array {
const unsigned int _size;
int _array[100];
public:
Array() : _size(100) {
for(unsigned int i = 0; i < _size; i++)
_array[i] = 0;
}
int& operator[](unsigned int index) {
cout << "normal operator[].\n";
return _array[index];
}
const int& operator[](unsigned int index) const {
cout << "const operator[].\n";
return _array[index];
}
};
int main()
{
Array a;
a[3] = 1;
cout << a[3] << "\n";
system("pause");
return 0;
}
“普通运算符[]”行执行了两次,但我希望第二次调用 (cout << a[3] << "\n";) 使用重载运算符的 const 版本,因为它不会更改数组本身。
这是为什么呢?有没有办法强制按我的意愿调用 const 版本?
【问题讨论】:
-
a在该表达式中不是const,因此不会调用 const 重载。如果你想强制它,你可以使用const_cast<Array const&>(a)[3],但它真的没有必要。 -
那有什么意义呢?我试图模仿 std::vector 因为它还有两个重载的 operator[] 函数。您是说除非 std::vector 对象是 const (因为我认为这没有意义),否则将始终调用非常量版本?
-
unless the std::vector object is const the non-const version will always be called这是(某种程度上)const重载的定义,是的。请注意,底层对象本身可能是非常量的,并且通过 const 引用进行访问,这通常是这种情况。例如,在您的代码中,您也可以使用Array const& b = a; cout << b[3]; -
现在说得通了。谢谢!
标签: c++