【问题标题】:Use of "this" keyword in template class在模板类中使用“this”关键字
【发布时间】:2018-03-24 07:47:21
【问题描述】:

我已经定义了一个模板类,并且重载了一个操作符,这样:

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&lt;double&gt; u = t.pow(2); 的内容时,我收到一条错误消息,指出invalid operands of types 'SparseMatrix&lt;bool&gt;*' and 'SparseMatrix&lt;bool&gt;*' to binary 'operator*'。正如我之前所说,bool 矩阵的乘法定义很好,那么,为什么编译器会抱怨呢?我对this 的使用不当吗?我该如何解决这个错误?

感谢您的帮助。

【问题讨论】:

  • 您似乎忘记了this 是指向对象的指针。如果您真的阅读了错误消息(其中提到了 SparseMatrix&lt;bool&gt;* 类型),应该非常明显。
  • 顺便说一句,所有const 都不见了。
  • 如果你实现operator*=()operator*(),你会发现它更容易和更有效。

标签: c++ class templates compiler-errors


【解决方案1】:

this 是指向对象的指针,而不是对象本身。取消引用 this 应该可以解决问题。

【讨论】:

    猜你喜欢
    • 2016-06-05
    • 2019-10-10
    • 2012-03-03
    • 2013-10-13
    • 1970-01-01
    • 1970-01-01
    • 2019-11-18
    • 2016-02-19
    • 2013-01-17
    相关资源
    最近更新 更多