J
J
jspie2017-06-23 00:17:50
C++ / C#
jspie, 2017-06-23 00:17:50

How to overload the + operator?

Such a question... there is a class A. It stores a dynamic one-dimensional array. There are two class instances with different arrays. How correctly to implement for example such MyClass c = a+b
In an overload the repeating elements of an array a,b should write down in a new array. The overload must return a class with a new array. How to do it correctly?
Returns an empty array:

Vect &Vect::operator+(const Vect &ob)
{
  Vect v;
  int j = 0;
  v.size = ob.size;
  v.vec = new int[v.size];
  for (int i = 0; i < v.size; i++){
    if (this->vec[i] == ob.vec[i])
      v.vec[j] = this->vec[i];
    j++;
  }

  return v;
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
nekipelov, 2017-06-23
@nekipelov

You're returning a reference to a local object, so you can't. The compiler should have warned about this. Correctly something like this (not seeing your class, I can be wrong):

Vect operator+(const Vect &lhs, const Vect &rhs)
{
  Vect v;

  v.size = lhs.size + rhs.size;
  v.vec = new int[v.size];

  std::copy(lhs.vec, lhs.vec + lhs.size, v.vec);
  std::copy(rhs.vec, rhs.vec + rhs.size, v.vec + lhs.size);

  return v;
}

D
Denis Zagaevsky, 2017-06-23
@zagayevskiy

What is the meaning of "empty array"?
Your array will be filled only if there are identical elements in the same places in the arrays. In all other cases, the array will contain zeros.
You don't check that this.size>=ob.size, but act like it does. May crash.
The + operator has different semantics. It would be better to use the & operator for this -- it can denote an intersection.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question