In general, I implement the matrix class, I overload the addition and assignment operators in order to add two matrices and assign thirds as a result of the following action: C = A + B, but the assignment operator does not work. Only in a separate expression. Program Code:
#include <iostream> #include <locale.h> #include <cstdlib> #include <ctime> using namespace std; class Matrix { public: const static size_t n = 4; double arr[n][n]; Matrix() { for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) { arr[i][j] = 0; } } Matrix(int k) { for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) { arr[i][j] = rand()%101 ; } } void showArr(char); Matrix operator + (Matrix &a); Matrix operator = (Matrix &a); float operator[] (size_t i) { return arr[i][i]; } }; int main() { srand(time(NULL)); setlocale(0, ""); char A[2] = { "A" }; char B[2] = { "B" }; char C[2] = { "C" }; Matrix a(1); Matrix b(2); Matrix c; a.showArr(A[0]); b.showArr(B[0]); c=a+b; c.showArr(C[0]); system("pause"); } Matrix Matrix::operator+ (Matrix& a) { double c[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) a.arr[i][j]+= arr[i][j]; } return *this; } Matrix Matrix :: operator = (Matrix &a) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) arr[i][j] = a.arr[i][j]; } return *this; } void Matrix::showArr(char A) { cout << "Матрица " << A << ":" << endl; for (int i = 0; i < n; i++) { if (i == 0) { for (int j = 0; j < n; j++) if (arr[i][j] >= 10) { cout << arr[i][j] << " "; } else cout <<" "<< arr[i][j] << " "; } else { cout << endl; for (int j = 0; j < n; j++) if (arr[i][j] >= 10) { cout << arr[i][j] << " "; } else cout << " " << arr[i][j] << " "; } } cout << endl<< endl; }
Matrix(int k)- just like the creators of the increment overload - but let's give us some garbage with an argument, just to distinguish, but we won't use it anyway. - Qwertiy ♦char A[2] = { "A" };- there is something wrong with the types. - Qwertiy ♦