如何用泛型类中的友元函数重载操作符

How to overload an operator with a friend function in a generic class?

本文关键字:函数 重载 操作符 友元 何用 泛型类      更新时间:2023-10-16

我写了一个矩阵类。我重载了运算符+,这样用户就可以写:矩阵+ 2。我希望用户也写:2 +矩阵。

对于标准格式(即对象调用2),我写了一个标准的操作符重载函数。它的工作原理。

template<typename T>
Matrix<T> Matrix<T>::operator+(const T& rhs) const
{
    Matrix result(rows, cols, 0.0);
    for (unsigned i = 0; i < rows; ++i)
    {
        for (unsigned j = 0; j < cols; ++j)
        {
            result(i,j) = (*this)(i, j) + rhs;
        }
    }
    return result;
}
现在对于另一阶(即2 +矩阵),我写了朋友函数:
// Friend Functions that allow the user to write expressions in a different order 
    template<typename T>
    friend Matrix<T> operator+(const T& type, const Matrix<T>& matrix);

和实现如下:

template<typename T>
Matrix<T> operator+(const T& type, const Matrix<T>& matrix) 
{
    return matrix + type;
}

当我尝试写2 +矩阵(在main()),我得到一些错误。

我总是在使用泛型类的友元函数时遇到问题,坦率地说,我一直不明白为什么它对我不起作用。

谁能解释一下我在这里做错了什么?

错误我得到:

智能感知:没有操作符"+"匹配这些操作数操作数类型为:int + Matrix

严重性代码描述项目文件行错误C2244 'Matrix::operator +':无法将函数定义与现有声明匹配

这看起来只是一个模板演绎错误;也就是说,编译器不能根据模板化的友元函数推断出正确的函数。

因为你的朋友函数是一个简单的函数,你可以在你的类/头文件中声明它,编译器应该能够正确地推断它(如果打开了优化,也可能内联它);只需在头文件中声明friend函数:

friend Matrix operator+(const T& type, const Matrix& matrix)
{
    return matrix + type;
}

你不需要指定template关键字,因为它在你的模板特化类中。

希望能有所帮助。

只需将成员函数更改为const即可解决此问题。

template<typename T>
Matrix<T> Matrix<T>::operator+(const T& rhs) const
{
   ...
}