我目前正在学校用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];
}