c++ - 如何在泛型类中用友元函数重载运算符?

标签 c++ overloading operator-keyword friend

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

对于标准格式(即对象调用 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() 中)时,出现了一些错误。

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

有人可以解释一下我在这里做错了什么吗?

我得到的错误:

IntelliSense: 没有运算符“+”匹配这些操作数操作数类型是:int + Matrix

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

最佳答案

看起来只是模板推导错误;也就是说,您的编译器无法根据模板化友元函数推断出正确的函数。

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

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

您不需要指定 template 关键字,因为它在您的模板专用类中。

希望对您有所帮助。

关于c++ - 如何在泛型类中用友元函数重载运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31900627/

相关文章:

java - 传递 null 时将在重载期间调用哪个方法

c++ - 为什么调用了不合适的重载函数?

c++ - 解析分配给默认参数值的重载函数时考虑了哪些函数集?

c++ - C++ 中的自减运算符

c++ - 第一次使用数组时,出现错误 'x was not declared in this scope' 但是我确实声明了它?

c++ - 使用 jsoncpp 将字符串映射转换为 json

c++ - 用两个参数重载 operator bool 是什么意思?

c++ - C++ 中链表的重载运算符 +=

c++ - 什么占用更多空间: Object or Struct?

c++ - 关于 C++ STL 中的类型