c++ - 无法使用 this 指针在对象上使用重载的 [] 运算符

标签 c++ operator-overloading this

我在重载 + 运算符和重载 [] 运算符时遇到问题。 [] 函数在 OrderedList 右对象上使用时工作正常,但在与 this 指针一起使用时我无法让它返回正确的值。

代码在 main 中的工作方式类似于: 列表 3 = 列表 1 + 列表 2

其中 list2 在参数列表中变为“正确”,我正在尝试使用 this 指针获取 list1 下标处的值。

我得到的错误是“无法将 OrderedList 转换为 double in assignment”,但我不确定它为什么要尝试分配 OrderedList?

非常感谢任何帮助,谢谢。

OrderedList OrderedList::operator+(OrderedList &right)
{
    int size1 = this -> _size;
    int size2 = right.getSize();
    double x, y;
    y = right[size2];
    x = this[size1];
    OrderedList list3;
    return list3;
}

double OrderedList::operator[](int subscript) const // returns rvalue 
{
    int x = OrderedList::_size;
    if (subscript > x)
    {
        cout << "Error: number is bigger than the size of the list" << endl;
    }
    else
    {
        Node* temporary = OrderedList::getListHead();
        for (int counter = 1; counter < subscript; counter++)
        {
            temporary = temporary -> next;
        }
        double nodeValue = temporary -> item;
        return nodeValue;
    }
}

最佳答案

this 是一个指针,所以您尝试执行 this[size1] 的原因是在执行指针运算。思考:

int a[] = {0, 1};
int *b[2] = &a;

要从 b 获取实际数据,我们必须先取消引用它:

int c = (*b)[1];

同样在这里我们必须取消引用this:

x = (*this)[size1];

关于c++ - 无法使用 this 指针在对象上使用重载的 [] 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23761214/

相关文章:

c++ - 编译器错误 : 'expected unqualified-id before "using '''

c++ - 使用 win32 api 向 rich edit 控件添加格式

c++ - 重载二元运算符作为模板类 : Not recognized as friend or linker error 的友元

javascript - 理解 RequireJS 中的上下文

javascript - jQuery 关键字 "this"取不到属性值

c++ - 二维数组— “Too many initializer values”警告/错误

c++ - 语法错误 : missing ';' before identifier 'PVOID64' when compiling winnt. h

C++——插入运算符、const关键字导致编译器错误

c++ - 如何在 C++ 中重载非交换运算符的两种可能性?

javascript - 示例 JS 函数中的 "this"是什么?