【发布时间】: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<T>::operator * (...)是一个member 函数,而不是一个独立函数。您需要定义template<typname T> Matrix<T> operator * (T t, const Matrix<T> &m)。此外,您的声明也需要是一个模板。
标签: c++ generics operator-overloading friend