所以我在尝试调用特定接线员时遇到了问题。在某些类(class)中,我得到:
template <class Object>
const Object& MyVector<Object>::operator[] (int index ) const {
if (index < 0 || index >= mSize)
throw MyException();
return mObjects[index];
}
我也得到了
template <class Object>
Object& MyVector<Object>::operator[]( int index ){
if (index < 0 || index >= mSize)
throw MyException();
return mObjects[index];
}
我想调用第二个,以便我可以修改值,但编译器一直告诉我不能这样做,因为我正在尝试修改常量。
这是我尝试使用运算符函数的地方:
template <class Object>
const Object& Matrix<Object>::get(int r, int c) const{
MyObject *row = & MyVectorObject[r]; //error
//snipped
}
我不断收到错误:无法从 const MyObject *
转换为 MyObject *
最佳答案
要调用对象的非常量成员函数(包括运算符),对象/引用必须是非常量。如果通过指针调用函数,则它必须是指向非常量的指针。
在您的情况下,MyVectorObject
是 const,因此调用了 const 重载。从您的代码中看不出来,为什么它是 const,但在注释中您表明它是一个成员。成员通过 this
指针隐式访问,并且在 const 成员函数内部 this
当然是指向 const 的指针。
关于c++ - 如何调用非常量运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26275995/