在模板类

问题描述:

使用“this”关键字的我已经定义了一个模板类,和重载运营商,以这样的方式在模板类

template<class T = bool> 
class SparseMatrix 
{ 
public: 
    SparseMatrix(int msize); 
    //Multiplication by vectors or matrices 
    SparseMatrix<double> operator *(SparseMatrix<T> &s); 
    //Matrix exponentiation 
    SparseMatrix<double> pow(int n); 
}; 

运营商的具体形式并不重要,我想。随着运营商超载,现在我可以做这样的事情:

int main(void) 
{ 
    int i; 

    SparseMatrix<bool> s = SparseMatrix<bool>(4); 
    SparseMatrix<bool> t = SparseMatrix<bool>(4); 

    //Here goes some code to fill the matrices... 

    SparseMatrix<double> u = t*s; //And then use the operator 

    return 0; 
} 

这工作得很好。没有错误,它返回正确的结果,等等。但是现在,我要填充类的pow方法,用这种方法:

template<class T> 
SparseMatrix<double> SparseMatrix<T>::pow(int n) 
{ 
    if (n == 2) 
    { 
     return (this * this); //ERROR 
    } 
    else 
    { 
     int i=0; 
     SparseMatrix<double> s = this * this; 

     while (i < n-2) 
     { 
      s = s * this; 
      i++; 
     } 
     return s; 
    } 

} 

然而,当我去main和喜欢写东西SparseMatrix<double> u = t.pow(2);我得到说错误invalid operands of types 'SparseMatrix<bool>*' and 'SparseMatrix<bool>*' to binary 'operator*'。正如我之前所说的,乘法是为bool矩阵定义明确的,所以,编译器为什么抱怨?我是否在使用this?我该如何解决这个错误?

谢谢你的帮助。

+4

你似乎忘记了'this'是对象的*指针*。如果你真的阅读错误信息(提到'SparseMatrix *'的类型),应该非常明显。 –

+0

顺便说一句,所有'const'都不见了。 – Jarod42

+0

如果你实现'operator * =()'和'operator *()',你会发现它更容易和更高效。 –

this是一个指向对象的指针,而不是对象本身。 Dereferincing this应该做的伎俩。