0

I'm trying to overload a operator + to add two arrays. I stacked when I try add two arrays (one copy).

class A{
    int *const e;
    const int row, column;
    public:
        A::A(int r, int c) : row(r), column(c), e(new int[r*c])
        {
            for (int i = 0; i < r*c; i++)
            {
                e[i] = 0;
            }
        }
        virtual A operator+(const A& a)const
        {
            A copy = *this;
            for (int i = 0; i < copy.row*copy.column; i++)
            {
                //copy.e
            }
            return (copy);
        }
        virtual int *const operator[ ](int r) //get the address of the 1st element of row r
        {
            return &e[r*row];
        }
}

But I cant figure out how to end add two arrays.

mskuratowski
  • 4,014
  • 15
  • 58
  • 109
  • And what exactly do you mean by adding them, adding them like matrices, only adding elements at the same positions or maybe something else? – Kelm Dec 04 '14 at 05:40
  • `A copy = *this;` is all wrong, you'd be doing a shallow copy, when what you want is a deep copy. You're better off using `std::vector`. – legends2k Dec 04 '14 at 05:40
  • Why are the operators virtual? – Shoe Dec 04 '14 at 05:47
  • Allocate some memory and forget about it huh? I suppose you've never heard about the [Rule of Three](http://stackoverflow.com/q/4172722/241631)? Please do yourself a favor and forget about `new` for a long time. Use an `std::vector` instead and you might be able to get the code to work. – Praetorian Dec 04 '14 at 05:47
  • You should generally initialize members in order of their declaration to be clear on what is and isn't initialized yet. If someone were to come along and change it to `e(new int[row*column])`, it would be using uninitialized members, despite them appearing before that. – chris Dec 04 '14 at 05:52
  • I've improved your code to do what you want - see it at [ideone.com](http://ideone.com/kDJ6sq). Still, using `std::vector` is a much better idea... will simplify things considerably and make the code much less fragile. – Tony Delroy Dec 04 '14 at 06:14

0 Answers0