Overloading "+" in a class.

Hello!!

I'm creating Array2D class. I'm using this peace of code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
template <typename T>
class Array2D
{
public:
  // constructor
  Array2D(unsigned wd,unsigned ht)
    : nWd(wd), nHt(ht), pAr(0)
  {
    if(wd > 0 && ht > 0)
      pAr = new T[wd * ht];
  }

  // destructor
  ~Array2D()
  {
    delete[] pAr;
  }


// indexing (parenthesis operator)
  //  two of them (for const correctness)

  const T& operator () (unsigned x,unsigned y) const
  {  return pAr[ y*nWd + x ];   }

  T& operator () (unsigned x,unsigned y)
  {  return pAr[ y*nWd + x ];   }

// get dims
  unsigned GetRows()  const { return nWd; }
  unsigned GetColns() const { return nHt; }


// private data members
private:
  unsigned nWd;
  unsigned nHt;
  T*       pAr;

  // to prevent unwanted copying:
  Array2D(const Array2D<T>&);
  Array2D& operator = (const Array2D<T>&);
};


It wasn't written by me, but it works good. I am just starting to learn how to overload parameters.
Can you please help, and, as an example, create an overloaded "+" operator?

Will it be something like this?

1
2
3
4
5
6
7
8
9
10
 template<typename R> Array2D<T> operator+(const Array2D<R> &A)const{
   Array2D<int> result(nWd,nHt) ;
   for(unsigned i = 0; i<nWd ; ++i){
    for(unsigned j = 0; j<nHt ; ++j){
      result(i,j) = A(i,j) + pAr[i*nWd + j] ;
				  }
				}
 return result;
}
Will it be something like this?

You'll answer this your self if you compiled and tested.

Where does nWd,nHt come from in code sample 2. It should be result (A.GetRows(),A.GetColns()

Also, operator() only returns data. It does not set.
Last edited on
The canonical way to implement operator+ is to write it as a non-member function and implement it by using operator+=, which is a member function.

Note:
The C++11 syntax to prevent unwanted copying:
1
2
  Array2D(const Array2D<T>&) = delete;
  Array2D& operator = (const Array2D<T>&) = delete;

Even if copying is not allowed, one could consider move operations ...
Topic archived. No new replies allowed.