C++矩阵运算题,求大神解答
矩阵运算设有两个3行3列矩阵A、B,求两矩阵的和、差、乘。
A+B=(aij+bij)
A- B=(aij-bij)
#include <iostream> template<typename T, size_t ROW, size_t COL> class Matrix; template<typename T, size_t ROW, size_t COL> std::ostream& operator<<( std::ostream& os, const Matrix<T,ROW,COL>& m ); template<typename T, size_t ROW, size_t COL> class Matrix { public: Matrix() { for( size_t r=0; r!=ROW; ++r ) for( size_t c=0; c!=COL; ++c ) value_[r][c] = T(); } Matrix( const std::initializer_list<T>& list ) { auto itor = std::begin(list); for( size_t r=0; r!=ROW; ++r ) for( size_t c=0; c!=COL; ++c ) if( itor != std::end(list) ) value_[r][c] = *itor++; else value_[r][c] = T(); } Matrix operator+( const Matrix& m ) const { Matrix ret; for( size_t r=0; r!=ROW; ++r ) for( size_t c=0; c!=COL; ++c ) ret.value_[r][c] = value_[r][c]+m.value_[r][c]; return ret; } private: T value_[ROW][COL]; friend std::ostream& operator<< <T,ROW,COL> ( std::ostream& os, const Matrix<T,ROW,COL>& m ); }; template<typename T, size_t ROW, size_t COL> std::ostream& operator<<( std::ostream& os, const Matrix<T,ROW,COL>& m ) { for( size_t r=0; r!=ROW; ++r ) { for( size_t c=0; c!=COL; ++c ) os << m.value_[r][c] << '\t'; os << '\n'; } return os; } using namespace std; int main( void ) { Matrix<int,3,3> m1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; Matrix<int,3,3> m2 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; cout << m1 << endl; cout << m2 << endl; cout << m1+m2 << endl; return 0; }输出
1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 2 4 6 8 10 12 14 16 18