您可以使用成员函数或非成员函数重载+运算符。
当它是一个成员函数时,运算符的LHS是函数将被调用的对象,而运算符的RHS是该函数的参数。因此,成员函数的唯一参数是RHS。
当它是成员函数时,运算符的LHS是该函数的第一个参数,而运算符的RHS是该函数的第二个参数。
成员函数
template<typename T>
class Matrix
{
Matrix operator+(const Matrix& rhs) const {
...
}
};
如果你想实现它的类定义之外,你可以使用:
template<typename T>
Matrix<T> Matrix<T>::operator+(const Matrix& rhs) const {
...
}
非成员函数
template<typename T>
class Matrix
{
Matrix operator+(const Matrix& lhs, const Matrix& rhs) {
...
}
};
如果你w蚂蚁来实现它的类定义之外,你需要添加一些前瞻性声明代码:
// Forward declare the class template
template <typename T> class Matrix;
// Declare the function
template <typename T> Matrix<T> operator+(const Matrix<T>& lhs, const Matrix<T>& rhs);
// Declare the friend in the class definition
template <typename T>
class Matrix
{
friend Matrix operator+<T>(const Matrix& lhs, const Matrix& rhs);
// ^^^^
// This makes operator+<int> a friend of Matrix<int>, not a friend
// of Matrix<double>
};
,然后实现功能
template <typename T> Matrix<T> operator+(const Matrix<T>& lhs, const Matrix<T>& rhs)
{
...
}
采用这种设置,oprator+<int>
是Matrix<int>
一个朋友而已,不是friend
的Matrix<double>
。
如果使用
template <typename U>
friend
Matrix<U> operator+(const Matrix<U>& a, const Matrix<U>& b);
届时,operator+
所有实例都是Matrix
所有实例,你并不需要的朋友。
更新
样品工作代码:
#include <iostream>
// Forward declare the class template
template<typename T> class Matrix;
// Declare the function
template <typename T> Matrix<T> operator+(const Matrix<T>& lhs, const Matrix<T>& rhs);
// Declare the friend in the class definition
template <typename T>
class Matrix
{
friend Matrix operator+<T>(const Matrix& lhs, const Matrix& rhs);
// ^^^^
// This makes operator+<int> a friend of Matrix<int>, not a friend
// of Matrix<double>
};
template <typename T> Matrix<T> operator+(const Matrix<T>& lhs, const Matrix<T>& rhs)
{
return Matrix<T>{};
}
int main()
{
Matrix<int> a;
Matrix<int> b;
Matrix<int> c = a + b;
}
相关:http://stackoverflow.com/questions/34663785/c-operator-overload –