[英]Assign a value to a specific element in a custom vector class. As a[5] = 3 C++
我目前正在学校用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];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.