为自定义向量类中的特定元素指定一个值.作为a[5]=3 C++

Assign a value to a specific element in a custom vector class. As a[5] = 3 C++

本文关键字:作为 一个 C++ 向量 自定义 元素      更新时间:2023-10-16

我目前正在学校用C++做一个练习。目标是编写一个向量类的自己的实现。

从测试文件中,我应该能够给一个元素一个特定的值。

    a[5] = 7;              // element 5 of vector a should hold value 7.

我不确定我是先打a[5]还是先打operator =

从我自己的班级我有

int myvec::operator[](int i) {
    return arr[i];
}

它返回i处的元素。但我不知道如何给它= 7的值。

我读到的内容似乎是operator = (this)内置了某种左操作数?

因此,如果有人能帮我分配元素i的值,我将非常感激

亲切问候

与其返回新值,不如让它返回对元素的引用:

int& myvec::operator[](int i) {
    return arr[i];
}

也可以考虑使用std::size_t作为索引,而不是int

int& myvec::operator[](int i) 替换int myvec::operator[](int i)

您应该返回对元素的引用来更改它。

您可能还想为const编写另一个重载:

const int& myvec::operator[](int i) const /* const overload */
{
  assert(i >= 0);
  if(i > myvec.size() ) throw out_of_bound_exception;
  return arr[i];
}
int& myvec::operator[](int i)  /* Changeable */
{
  assert(i >= 0);
  if(i > myvec.size() ) throw out_of_bound_exception;
  return arr[i];
}