【问题标题】:unable to match function definition to an existing declaration in cpp无法将函数定义与 cpp 中的现有声明匹配
【发布时间】:2015-01-17 16:12:25
【问题描述】:

我正在做一个课程项目,我在 cpp 中创建了一个带有二维向量的矩阵类。 我正在尝试使用矩阵 obj 将 * 运算符覆盖为全局运算符。

这是我的声明:

friend Matrix<T> operator * (T t, const Matrix<T> &m);

这就是函数:

template <typename T>
Matrix<T> operator * (T t, const Matrix<T> &m)
{
    int i, j;
    Matrix<T> ans(rows, cols);
    for (i = 0; i < rows; i++)
    {
        for (j = 0; j < rows; j++)
        {
            ans[i][j] = t * m.mat[i][j];
        }
    }
return ans;
}

我的错误是:错误 C2244: 'Matrix::operator *' : 无法将函数定义与现有声明匹配

我的代码有什么问题??

【问题讨论】:

  • 那是因为Matrix&lt;T&gt;::operator * (...) 是一个member 函数,而不是一个独立函数。您需要定义template&lt;typname T&gt; Matrix&lt;T&gt; operator * (T t, const Matrix&lt;T&gt; &amp;m)。此外,您的声明也需要是一个模板。

标签: c++ generics operator-overloading friend


【解决方案1】:

您声明的 friend 函数虽然在类中,但不是成员函数。
像这样调整定义:

template <typename T>
Matrix<T> operator * (T t, const Matrix<T> &m)
{
    // […]
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-11
    • 1970-01-01
    • 2013-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-19
    相关资源
    最近更新 更多