简体   繁体   English

如何调用非常量运算符?

[英]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 * 我不断收到错误:无法从const MyObject *转换为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. 在您的情况下, MyVectorObject是const,因此调用了const重载。 It's not apparent from your code, why it is const, but in the comments you reveal that it is a member. 从代码中看不出来为什么它是const,但是在注释中却表明它是成员。 Members are implicitly accessed through this pointer and inside const member functions this is of course a pointer to const. 通过this指针隐式访问成员,而在const成员函数内部, this当然是指向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. Matrix<Object>::get()方法是const,因此,如果您在该方法中访问Matrix的类属性,则所有这些属性都将被视为const。

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

const Object& MyVector<Object>::operator[] (int index ) const will return a const Object& . const Object& MyVector<Object>::operator[] (int index ) const将返回一个const Object&

So MyVectorObject[r] is of type const Object& and & MyVectorObject[r] will be of type const Object * 因此, MyVectorObject[r]的类型为const Object&& MyVectorObject[r]的类型为const Object *

You should write: const MyObject *row = & MyVectorObject[r]; 您应该这样写: const MyObject *row = & MyVectorObject[r];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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