我在重载 + 运算符和重载 [] 运算符时遇到问题。 [] 函数在 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/