tags:

views:

124

answers:

2

How do I write a program to overload the + operator so that it can add two matrices?

+1  A: 

From http://www.parashift.com/c++-faq-lite/operator-overloading.html#faq-13.1

The idea is to call functions using the syntax of C++ operators. Such functions can be defined to accept parameters of user-defined types, giving the operators user-defined meaning. For example:

Matrix add(const Matrix& x, const Matrix& y);
Matrix operator+(const Matrix& x, const Matrix& y);
Matrix use_add(const Matrix& a, const Matrix& b, const Matrix& c)
{
  return add(a,add(b,c));
}
Matrix use_plus(const Matrix& a, const Matrix& b, const Matrix& c)
{
  return a + b + c;
}

Also, this forum thread from lansinwd discusses this in detail

Espo
Note that the code provided is not from the current C++ FAQ, but from what seems to be an older version. (One reason they probably changed the example is that `use_add()` and `use_plus()` aren't exactly identical.)
sbi
A: 

The idiomatic way to overload operators is the following.

struct M {
   ...
   M & operator+=(M const& rhs) {
       loop * 2 to increment
       return this;
   }
};

M operator+(M lhs, M const& rhs) {
    return lhs += rhs;
}

But have a look at Blitz++, newmat and boost solutions that eliminate temporary objects thanks to Expression Templates -- C++0x's rvalue references will simplify ET solution.

NB: You will prefer to implement op*= in terms of op* instead of the other way around.

Luc Hermitte
Using `M operator+( M lhs, M const return lhs; }` (as a two liner instead of a one liner) improves the compiler changes of optimizing copies away: it is clear that the returned reference is `lhs`. If you implement it as a one-liner the compiler cannot guess whether the returned reference from `lhs+=rhs` is actually a reference to `lhs` or any other object. (Tests with g++-4.3.3 -O3 show no difference anyway)
David Rodríguez - dribeas