C ++ ::重载运算符*用于矩阵 - 向量乘法

时间:2012-11-01 23:41:59

标签: c++ matrix-multiplication

我想重载operator *进行矩阵 - 向量乘法。这是我的Vector和Matrix类:

class Vec2
{
  public:
    Vec2(){}
    Vec2(const RealNumber& a, const RealNumber& b)
    {
      a_ = a; b_ = b;
    }

    Vec2& operator =  (const Vec2& B)
    {
      a_ = B.a_;
      b_ = B.b_;
      return(*this);
    }

    void a(const RealNumber& a){
      a_ = a;
    }

    void b(const RealNumber& b){
      b_ = b;
    }

    const RealNumber a(void){
      return(a_);
    }

    const RealNumber b(void){
      return(b_);
    }

  private:
    RealNumber a_,b_;
};

和矩阵类:

class Mat2x2
{
  public:
    Mat2x2(){}
    Mat2x2(const RealNumber& a,
           const RealNumber& b,
           const RealNumber& c,
           const RealNumber& d)
    {
      a_ = a; b_ = b; c_ = c; d_ = d;
    }

    Mat2x2& operator =  (const Mat2x2& B)
    {
      a_ = B.a_;
      b_ = B.b_;
      c_ = B.c_;
      d_ = B.d_;
      return(*this);
    }

    const RealNumber a(void){
      return(a_);
    }

    const RealNumber b(void){
      return(b_);
    }

    const RealNumber c(void){
      return(c_);
    }

    const RealNumber d(void){
      return(d_);
    }
    // compile time problem with this overloading function
    const Vec2 operator * (const Vec2& B) const {
      Vec2 result;
      result.a(this->a_*B.a()+this->b_*B.b());
      result.b(this->c_*B.a()+this->d_*B.b());
      return result;
    }    

  private:
    RealNumber a_,b_,c_,d_;
};

我用g++编译代码并得到以下错误:

error: passing ‘const rln::Vec2’ as ‘this’ argument of ‘const rln::RealNumber rln::Vec2::a()’ discards qualifiers [-fpermissive]

我无法弄清楚如何解决问题。

1 个答案:

答案 0 :(得分:3)

设置您的访问者功能const,如下所示:

RealNumber a() const { return a_; }
//             ^^^^^

(顺便说一下,不需要返回值const;实际上,这是C ++ 11中不推荐使用的模式。只需保持简单。)