[英]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.