2012-11-01 78 views
0

我想重载运算符*为矩阵 - 向量乘法。这里是我的向量和矩阵类:C++ ::重载运算符*为矩阵 - 向量乘法

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

您应该了解构造函数初始值设定项列表。 –

回答

3

让您的访问函数const,就像这样:

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

(顺便说一句,没有必要为了使返回值const;事实上,这是在C++ 11已过时的模式只要保持它的简单。 )

+0

谢谢!它解决了这个问题。顺便一提!如果我从返回值中省略const(返回值也是另一个类而不是内置类型),那么'lvalue'赋值是合法的,不会? – Rasoul

+0

@Rasoul:我不确定我们是否同意“左值赋值”应该是什么意思,但实际上,有一小部分常量返回值禁止的构造。尽管如此,我从来没有见过这样一种情况,即那会帮助任何人或阻止重大灾难。 –