开发者

How to do operator overloading

开发者 https://www.devze.com 2022-12-09 03:08 出处:网络
How do I write a program to overload the + operator so that it can开发者_运维百科 add two matrices?From http://www.parashift.com/c++-faq-lite/operator-overloading.html#faq-13.1

How do I write a program to overload the + operator so that it can开发者_运维百科 add two matrices?


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消