0

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

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]

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

4

1 回答 1

3

使您的访问器函数const,如下所示:

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

(顺便说一句,没有必要制作返回值const;事实上,这是 C++11 中不推荐使用的模式。保持简单即可。)

于 2012-11-01T23:44:57.270 回答