矩阵类(运算符+-及输入输出重载).cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #include <iostream>
  2. #include <iomanip>
  3. class Matrix {
  4. private:
  5. int data[2][3];
  6. public:
  7. // 默认构造函数,初始化矩阵为0
  8. Matrix() {
  9. for (int i = 0; i < 2; ++i)
  10. for (int j = 0; j < 3; ++j)
  11. data[i][j] = 0;
  12. }
  13. // 重载输入运算符
  14. friend std::istream& operator>>(std::istream& in, Matrix& matrix) {
  15. for (int i = 0; i < 2; ++i) {
  16. for (int j = 0; j < 3; ++j) {
  17. in >> matrix.data[i][j];
  18. }
  19. }
  20. return in;
  21. }
  22. // 重载输出运算符
  23. friend std::ostream& operator<<(std::ostream& out, const Matrix& matrix) {
  24. for (int i = 0; i < 2; ++i) {
  25. for (int j = 0; j < 3; ++j) {
  26. out << std::setw(7) << matrix.data[i][j]; // 用这个什么setw设置宽度
  27. }
  28. out << std::endl;
  29. }
  30. return out;
  31. }
  32. // 重载加法运算符
  33. Matrix operator+(const Matrix& other) const {
  34. Matrix result;
  35. for (int i = 0; i < 2; ++i) {
  36. for (int j = 0; j < 3; ++j) {
  37. result.data[i][j] = this->data[i][j] + other.data[i][j];
  38. }
  39. }
  40. return result;
  41. }
  42. // 重载减法运算符
  43. Matrix operator-(const Matrix& other) const {
  44. Matrix result;
  45. for (int i = 0; i < 2; ++i) {
  46. for (int j = 0; j < 3; ++j) {
  47. result.data[i][j] = this->data[i][j] - other.data[i][j];
  48. }
  49. }
  50. return result;
  51. }
  52. };
  53. int main() {
  54. Matrix m1, m2;
  55. std::cout << "请输入2行3列矩阵内容:" << std::endl;
  56. std::cin >> m1;
  57. std::cout << "请输入2行3列矩阵内容:" << std::endl;
  58. std::cin >> m2;
  59. Matrix sum = m1 + m2;
  60. Matrix diff = m1 - m2;
  61. std::cout << "m1+m2=" << std::endl;
  62. std::cout << sum;
  63. std::cout << "m1-m2=" << std::endl;
  64. std::cout << diff;
  65. return 0;
  66. }