您可以使用成員函數或非成員函數重載+運算符。
當它是一個成員函數時,運算符的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 –