fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. template <typename T>
  5. class Matrix {
  6. protected:
  7. T** a;
  8. int size1;
  9. int size2;
  10.  
  11. public:
  12. Matrix(int n, int m) {
  13. while (n <= 0 && m <= 0) {
  14. cout << "Введіть інший розмір";
  15. cin >> n >> m;
  16. }
  17. size1 = n;
  18. size2 = m;
  19. a = new T* [n];
  20. for (int i = 0; i < n; i++) {
  21. a[i] = new T[m];
  22. }
  23. }
  24.  
  25. Matrix() : size1(1), size2(1) {
  26. a = new T* [1];
  27. a[0] = new T[1];
  28. }
  29.  
  30. ~Matrix() {
  31. for (int i = 0; i < size1; i++) {
  32. delete[] a[i];
  33. }
  34. delete[] a;
  35. }
  36.  
  37. T* operator[](const int i) { return a[i]; }
  38.  
  39. Matrix operator+(const Matrix& right ) const {
  40. Matrix result(size1, size2);
  41. for (int i = 0; i < size1; i++) {
  42. for (int j = 0; j < size2; j++) {
  43. result.a[i][j] = a[i][j] + right.a[i][j];
  44. }
  45. }
  46. return result;
  47. }
  48.  
  49. Matrix operator-(const Matrix& right) const {
  50. Matrix result(size1, size2);
  51. for (int i = 0; i < size1; i++) {
  52. for (int j = 0; j < size2; j++) {
  53. result.a[i][j] = a[i][j] - right.a[i][j];
  54. }
  55. }
  56. return result;
  57. }
  58.  
  59. Matrix operator*(const Matrix& right) const {
  60. Matrix result(size1, right.size2);
  61. for (int i = 0; i < size1; i++) {
  62. for (int j = 0; j < right.size2; j++) {
  63. result.a[i][j] = 0;
  64. for (int k = 0; k < size2; k++) {
  65. result.a[i][j] += a[i][k] * right.a[k][j];
  66. }
  67. }
  68. }
  69. return result;
  70. }
  71.  
  72. friend ostream& operator<< (ostream& os, const Matrix& a) {
  73. for (int i = 0; i < a.size1; i++) {
  74. for (int j = 0; j < a.size2; j++) {
  75. os << a.a[i][j] << " ";
  76. }
  77. os << endl;
  78. }
  79. return os;
  80. }
  81.  
  82.  
  83. friend istream& operator>>(istream& is, const Matrix& a) {
  84. for (int i = 0; i < a.size1; i++) {
  85. for (int j = 0; j < a.size2; j++) {
  86. is >> a.a[i][j];
  87. }
  88. }
  89. return is;
  90. }
  91. };
  92.  
  93. template<typename T>
  94. class SquareMatrix : public Matrix<T> {
  95. public:
  96. SquareMatrix(int size) : Matrix<T>(size, size) {}
  97.  
  98. T trace() {
  99. T sum = 0;
  100. for (int i = 0; i < this->size1; i++) {
  101. sum += this->a[i][i];
  102. }
  103. return sum;
  104. }
  105. };
  106.  
  107. int main(void)
  108. {
  109. Matrix<double> a(4, 3);
  110. cin >> a;
  111. Matrix<double> b(4, 3);
  112. cin >> b;
  113. Matrix<double> c = a - b;
  114. cout << c;
  115. return 0;
  116. }
  117.  
Success #stdin #stdout 0s 5316KB
stdin
1 2 3
4 5 6
7 8 9
10 11 12
1 4 3
4 5 6
7 8 9
10 11 12
stdout
0 -2 0 
0 0 0 
0 0 0 
0 0 0