简体   繁体   中英

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++. 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 = .

From my own class I have

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

Which returns the element at i . But I do not know how to give it the value of = 7 .

What I've read there seems to be some kind of left operand built in to the operator = (this) ?

So if anyone could help me to assign the value of element i I would really appreciate it.

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.

Replace int myvec::operator[](int i) with 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 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];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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