编写2×2的矩阵Matrix,重载+(加法运算符)和*(乘法运算符)支持矩阵加法和乘法。矩阵加法可以正常支持,但是重载的乘法运算符跑不过去,会报错误:
代码如下:
#include <iostream>
using namespace std;
template <typename valtype>
class Matrix{
friend Matrix operator+ <valtype> (const Matrix& mat1, const Matrix& mat2);
friend Matrix operator* <valtype> (const Matrix& mat1, const Matrix& mat2);
public:
Matrix(const valtype* mat);
Matrix(valtype a11 = 0, valtype a12 = 0, valtype a21 = 0, valtype a22 = 0);
Matrix& operator+=(const Matrix& mat);
valtype operator()(int row, int col)const
{
row = row <= 2 ? row : 0;
col = col <= 2 ? col : 0;
return _mat[row][col];
}
valtype& operator()(int row, int col)
{
row = row <= 2 ? row : 0;
col = col <= 2 ? col : 0;
return _mat[row][col];
}
ostream& print(ostream& os = cout)const;
private:
valtype _mat[2][2];
};
template <typename valtype>
ostream& operator<<(ostream& os, const Matrix<valtype>& mat)
{
return mat.print(os);
}
template <typename valtype>
Matrix<valtype> operator+(const Matrix<valtype>& mat1, const Matrix<valtype>& mat2)
{
Matrix<valtype> tmp;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
tmp._mat[i][j] = mat1._mat[i][j] + mat2._mat[i][j];
}
}
return tmp;
}
template <typename valtype>
Matrix<valtype> operator*(const Matrix<valtype>& mat1, const Matrix<valtype>& mat2)
{
Matrix<valtype> tmp;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
for (int k = 0; k < 2; k++)
{
tmp._mat[i][j] += (mat1._mat[i][k]) * (mat2._mat[k][j]);
}
}
}
return tmp;
}
template <typename valtype>
Matrix<valtype>::Matrix(const valtype* mat)
{
int index = 0;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
_mat[i][j] = mat[index++];
}
}
}
template <typename valtype>
Matrix<valtype>::Matrix(valtype a11, valtype a12, valtype a21, valtype a22)
{
_mat[0][0] = a11; _mat[0][1] = a12;
_mat[1][0] = a21; _mat[1][1] = a22;
}
template <typename valtype>
Matrix<valtype>& Matrix<valtype>::operator+=(const Matrix& mat)
{
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
_mat[i][j] += mat._mat[i][j];
}
}
return *this;
}
template <typename valtype>
ostream& Matrix<valtype>::print(ostream& os)const
{
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
os << _mat[i][j] << ' ';
}
os << endl;
}
return os;
}
测试代码:
#include "laopo.h"
using namespace std;
int main()
{
Matrix<int> mat1(1, 2, 3, 4);
Matrix<int> mat2(5, 6, 7, 8);
cout << mat1 + mat2;
return 0;
}
要是把Marix中声明的乘法运算符友元函数和乘法运算符的定义都注释掉就可以运行。
请问是为什么啊???
在
std
里有 template operator+
,但是没有 template operator*
。所以直接使用 oeprator*
<T> 就报错了,因为 operator*
不是 template 。加前置声明吧: