c++ - 如何调用非常量运算符?

标签 c++ constants

所以我在尝试调用特定接线员时遇到了问题。在某些类(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/

相关文章:

c++ - 什么时候使用 c++ iostreams 而不是 ReadFile、WriteFile、fprintf 等...?

c++ - 概念可能会取代 C++ 中的类型特征吗?

java - 在java中传递泛型类类型

c++ - lambda 的生命周期在 const lambda 中捕获引用

const数组的C++长编译时间

c# - 如何使用 const int 属性的名称

c++ - Objective C 框架不导出某些类

c++ - 如何使用libc++用clang编译Google Benchmark

C++ 链接器提示 char* 的多个定义,但不是 std::string

C++ 重载 getter 两次,一次返回指针,一次返回 const 引用,失败