如何在泛型 class 中使用友元函数重载运算符?
How to overload an operator with a friend function in a generic class?
我写了一个矩阵class。我重载了运算符+,以便用户可以写: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() 中)时,出现一些错误。
我在使用泛型 classes 的友元函数时总是遇到问题,坦率地说,我一直不明白为什么它对我不起作用。
有人可以解释一下我做错了什么吗?
我得到的错误:
IntelliSense:没有运算符“+”匹配这些操作数操作数类型是:int + Matrix
严重性代码说明项目文件行错误 C2244'Matrix::operator +':无法将函数定义与现有声明相匹配
只需将成员函数更改为const
即可解决问题。
template<typename T>
Matrix<T> Matrix<T>::operator+(const T& rhs) const
{
...
}
看起来只是模板推导错误;也就是说,您的编译器无法根据模板化友元函数推断出正确的函数。
因为你的友元函数是一个简单的函数,你可以在你的 class/header 中声明它,编译器应该能够正确地推导它(如果打开了优化,也可能内联它);只需在 header 中声明好友函数,如下所示:
friend Matrix operator+(const T& type, const Matrix& matrix)
{
return matrix + type;
}
您不需要指定 template
关键字,因为它在您的模板专门 class.
中
希望能帮到你。
我写了一个矩阵class。我重载了运算符+,以便用户可以写: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() 中)时,出现一些错误。
我在使用泛型 classes 的友元函数时总是遇到问题,坦率地说,我一直不明白为什么它对我不起作用。
有人可以解释一下我做错了什么吗?
我得到的错误:
IntelliSense:没有运算符“+”匹配这些操作数操作数类型是:int + Matrix
严重性代码说明项目文件行错误 C2244'Matrix::operator +':无法将函数定义与现有声明相匹配
只需将成员函数更改为const
即可解决问题。
template<typename T>
Matrix<T> Matrix<T>::operator+(const T& rhs) const
{
...
}
看起来只是模板推导错误;也就是说,您的编译器无法根据模板化友元函数推断出正确的函数。
因为你的友元函数是一个简单的函数,你可以在你的 class/header 中声明它,编译器应该能够正确地推导它(如果打开了优化,也可能内联它);只需在 header 中声明好友函数,如下所示:
friend Matrix operator+(const T& type, const Matrix& matrix)
{
return matrix + type;
}
您不需要指定 template
关键字,因为它在您的模板专门 class.
希望能帮到你。