简体   繁体   中英

How to call a non-const operator?

So I'm having trouble trying to call a specific operator. In some class, I'm given:

template <class Object>
const Object& MyVector<Object>::operator[] (int index ) const {
    if (index < 0 || index >= mSize)
        throw MyException();
    return mObjects[index];
}

and I'm also given

template <class Object>
Object& MyVector<Object>::operator[]( int index ){
    if (index < 0 || index >= mSize)
        throw MyException();
    return mObjects[index];
}

I want to call the second one so I can modify the value, but the compiler keeps telling me that I can't do so because I'm trying to modify a constant.

Here's where I'm trying to use the operator function:

template <class Object>
const Object& Matrix<Object>::get(int r, int c) const{
    MyObject *row = & MyVectorObject[r]; //error
    //snipped
}

And I keep getting the error: cannot convert from const MyObject * to MyObject *

To call a non-const member function (including an operator) of an object, the object/reference must be non-const. If the function is called through a pointer, it must be a pointer to non-const.

In your case MyVectorObject is const and therefore the const overload was called. It's not apparent from your code, why it is const, but in the comments you reveal that it is a member. Members are implicitly accessed through this pointer and inside const member functions this is of course a pointer to const.

The Matrix<Object>::get() method is const, so if you access class attributes of Matrix in that method, all of them will be considered as const.

MyObject *row = & MyVectorObject[r] will effectively calls const Object& MyVector<Object>::operator[] (int index ) const .

const Object& MyVector<Object>::operator[] (int index ) const will return a const Object& .

So MyVectorObject[r] is of type const Object& and & MyVectorObject[r] will be of type const Object *

You should write: const MyObject *row = & MyVectorObject[r];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM