简体   繁体   English

为自定义矢量类中的特定元素分配值。 作为[5] = 3 C ++

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

I'm currently doing an exercise in school in C++. 我目前正在学校用C ++进行练习。 The object is to write an own implementation of a vector class. 目的是编写向量类的自己的实现。

From the test file I should be able to give an element a specific value. 从测试文件中,我应该能够为元素指定一个特定的值。

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

I'm not sure if I call a[5] first or the operator = . 我不确定是先调用a[5]还是要operator =

From my own class I have 我上课的时候

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

Which returns the element at i . 它返回i处的元素。 But I do not know how to give it the value of = 7 . 但是我不知道如何赋予它= 7的值。

What I've read there seems to be some kind of left operand built in to the operator = (this) ? 我读过什么,似乎在operator = (this)内置了某种左操作数?

So if anyone could help me to assign the value of element i I would really appreciate it. 所以,如果有人可以帮助我来分配元素的值i ,我真的很感激。

Kind regards 亲切的问候

Instead of returning a new value, simply make it return a reference to the element: 无需返回新值,只需使其返回对元素的引用即可:

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

Also instead of int consider using std::size_t for the index. 另外,也可以考虑使用std::size_t作为索引,而不是int

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

You should return the reference to the element to change it. 您应该返回对元素的引用以进行更改。

You may also want to write another overload for const as: 您可能还想为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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM