#include <iostream>
#include <vector>
using std::vector;
using MATRIX = vector<vector<int>>;
class Matrix {
public:
MATRIX matrix;
int row = matrix.size();
int col = matrix[0].size();
void repr() {
for (const vector<int> &sub_arr: matrix) {
for (int element: sub_arr) {
std::cout << element << ' ';
}
std::cout << '\n';
}
}
Matrix operator+(const Matrix &other) {
std::cout << row << col;
Matrix new_matrix;
if (row != other.matrix.size() || col != other.matrix[0].size()) { return {{}}; }
for (int i = 0; i < row; ++i) {
vector<int> temp_arr;
for (int j = 0; j < col; ++j) {
temp_arr.push_back(matrix[i][j] + other.matrix[i][j]);
}
new_matrix.matrix.push_back(temp_arr);
}
return new_matrix;
}
Matrix operator-(const Matrix &other) {
Matrix new_matrix;
if (row != other.matrix.size() || col != other.matrix[0].size()) { return {{}}; }
for (int i = 0; i < row; ++i) {
vector<int> temp_arr;
for (int j = 0; j < col; ++j) {
temp_arr.push_back(matrix[i][j] - matrix[i][j]);
}
new_matrix.matrix.push_back(temp_arr);
}
return new_matrix;
}
// Matrix operator*(const Matrix &other) {}
};
int main() {
Matrix matrix = {{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}};
Matrix addition = matrix + matrix;
addition.repr();
}
So when I define row and col at the class level, it doesn’t produce any output. But when I define it in the function, it works fine.
I don’t understand why it won’t work when I define it in the class level. I inserted some debug print statements, and row and col seem to be correct.
>Solution :
When row and col are initialized, matrix is still empty. To initialize them after matrix is known, write a constructor for your class.
#include <vector>
using std::vector;
using MATRIX = vector<vector<int>>;
class Matrix {
public:
MATRIX matrix;
int row, col;
// Constructor
Matrix(const MATRIX& m)
: matrix(m), row(m.size()), col(m[0].size())
{}
};
int main() {
Matrix matrix = {{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}};
}