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. // Перевантаження +
  40. Matrix operator+(const Matrix& left) const {
  41. Matrix result(size1, size2);
  42. for (int i = 0; i < size1; i++) {
  43. for (int j = 0; j < size2; j++) {
  44. result.a[i][j] = a[i][j] + left.a[i][j];
  45. }
  46. }
  47. return result;
  48. }
  49.  
  50. // Перевантаження -
  51. Matrix operator-(const Matrix& left) const {
  52. Matrix result(size1, size2);
  53. for (int i = 0; i < size1; i++) {
  54. for (int j = 0; j < size2; j++) {
  55. result.a[i][j] = a[i][j] - left.a[i][j];
  56. }
  57. }
  58. return result;
  59. }
  60.  
  61. // Перевантаження *
  62. Matrix operator*(const Matrix& right) const {
  63. Matrix result(size1, right.size2);
  64. for (int i = 0; i < size1; i++) {
  65. for (int j = 0; j < right.size2; j++) {
  66. result.a[i][j] = 0;
  67. for (int k = 0; k < size2; k++) {
  68. result.a[i][j] += a[i][k] * right.a[k][j];
  69. }
  70. }
  71. }
  72. return result;
  73. }
  74.  
  75. friend ostream& operator<<(ostream& x, const Matrix& a) {
  76. for (int i = 0; i < a.size1; i++) {
  77. for (int j = 0; j < a.size2; j++) {
  78. x << a.a[i][j] << " ";
  79. }
  80. x << endl;
  81. }
  82. return x;
  83. }
  84.  
  85. friend istream& operator>>(istream& is, const Matrix& a) {
  86. for (int i = 0; i < a.size1; i++) {
  87. for (int j = 0; j < a.size2; j++) {
  88. is >> a.a[i][j];
  89. }
  90. }
  91. return is;
  92. }
  93. };
  94.  
  95. template<typename T>
  96. class SquareMatrix : public Matrix<T> {
  97. public:
  98. SquareMatrix(int size) : Matrix<T>(size, size) {}
  99.  
  100. T trace() {
  101. T sum = 0;
  102. for (int i = 0; i < this->size1; i++) {
  103. sum += this->a[i][i];
  104. }
  105. return sum;
  106. }
  107. };
  108.  
  109. int main(void)
  110. {
  111. Matrix<double> a(4, 3);
  112. cin >> a;
  113. Matrix<double> b(3, 4);
  114. cin >> b;
  115. Matrix<double> c = a * b;
  116. cout << c;
  117. return 0;
  118. }
Success #stdin #stdout 0.01s 5280KB
stdin
1 2 3
4 5 6
7 8 9
10 11 12
1 0 0 1
0 1 1 0
1 0 1 1
stdout
4 2 5 4 
10 5 11 10 
16 8 17 16 
22 11 23 22