赞
踩
- #include <iostream>
- #include <string>
- using namespace std;
-
- class Matrix
- {
- friend Matrix operator+(Matrix& m1, Matrix& m2);
- friend Matrix operator-(Matrix& m1, Matrix& m2);
- friend Matrix operator*(Matrix& m1, Matrix& m2);
-
- //矩阵类的声明
- private:
- int m_r;
- int m_c;
- int m_Array[10][10];
- public:
- Matrix(int r, int c)
- {
- m_r = r;
- m_c = c;
- Fill(0);
- }
- void Fill(int value);
- void Set(int r, int c, int value);
- int Get(int r, int c);
- void Print();
- };
- //Matrix::Matrix(int r,int c):m_r(r),m_c(c){}
- //全部设值函数
- void Matrix::Fill(int value)
- {
-
- for (int i = 0; i < m_r; i++)
- {
- for (int j = 0; j < m_c; j++)
- {
- m_Array[i][j] = value;
- }
- }
- return;
- }
-
- //指定位置设值函数
- void Matrix::Set(int r, int c, int value)
- {
- m_Array[r][c] = value;
- }
-
- //获取元素函数
- int Matrix::Get(int r, int c)
- {
- return m_Array[r][c];
- }
-
- //打印函数
- void Matrix::Print()
- {
- for (int i = 0; i < m_r; i++)
- {
- for (int j = 0; j < m_c; j++)
- {
- cout << m_Array[i][j]<<" ";
- if (j == m_c - 1)
- {
- cout << endl;
- }
- }
- }
- }
-
- //实现矩阵加法
- Matrix operator+(Matrix& m1, Matrix& m2)
- {
- Matrix temp(m1.m_r, m1.m_c);
-
- for (int i = 0; i < m1.m_r; i++)
- {
- for (int j = 0; j < m1.m_c; j++)
- {
- temp.m_Array[i][j] = m1.m_Array[i][j] + m2.m_Array[i][j];
- }
- }
- return temp;
- }
-
- //实现矩阵减法
- Matrix operator-(Matrix& m1, Matrix& m2)
- {
- Matrix temp(m1.m_r, m1.m_c);
-
- for (int i = 0; i < m1.m_r; i++)
- {
- for (int j = 0; j < m1.m_c; j++)
- {
- temp.m_Array[i][j] = m1.m_Array[i][j] - m2.m_Array[i][j];
- }
- }
- return temp;
- }
-
- //实现矩阵乘法
- Matrix operator*(Matrix& m1, Matrix& m2)
- {
- Matrix temp(m1.m_r, m2.m_c);
- temp.Fill(0);
- for (int i = 0; i < m1.m_r; i++)
- {
- for (int j = 0; j < m2.m_c; j++)
- {
- for (int k = 0; k < m1.m_c; k++)
- {
- temp.m_Array[i][j] += m1.m_Array[i][k] * m2.m_Array[k][j];
- }
- }
- }
- return temp;
- }
-
- int main()
- {
- int i, j;
- cin >> i >> j;
- Matrix m1(i, j), m2(i, j), m3(j, i);
- m1.Fill(1);
- m2.Fill(2);
- m3.Fill(0);
- for (int s = 0; s < i; s++) {
- for (int c = 0; c < j; c++) {
- if (s == c)
- m3.Set(s, c, s + 1);
- }
- }
- m1.Print();
- m2.Print();
- m3.Print();
- cout << "m1 + m2 :" << endl;
- (m1 + m2).Print();
- cout << "m1 - m2 :" << endl;
- (m1 - m2).Print();
- cout << "m1 * m3 :" << endl;
- (m1 * m3).Print();
-
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。