This is some of the fundamental methods in my Matrix class.
I'm not sure what I have done with initEntries and/or initCopy is so elegant, and maybe there is some flexibility I should use and avoid these helper functions.
The partial CPP file:
Code:
#include "Matrix.h"
void Matrix::initEntries()
{
for (int i = 0; i < m_Dims.rows * m_Dims.cols; i++)
{
m_Entries[i] = 0;
}
}
void Matrix::initCopy(const Matrix &m) // I use this function also in operator= method!
{
for (int i = 0; i < m_Dims.rows * m_Dims.cols; i++)
{
m_Entries[i] = m.m_Entries[i];
}
}
Matrix::Matrix(int rows, int cols)
: m_Dims{rows, cols}, m_Entries(new float[rows * cols])
{
if (m_Dims.rows < 0 || m_Dims.cols)
initEntries();
};
Matrix::Matrix(const Matrix &m) // Copy constructor
: Matrix(m.m_Dims.rows, m.m_Dims.cols)
{
initCopy(m);
}
This is the header file:
Code:
#ifndef MATRIX_H
#define MATRIX_H
#include <iostream>
const std::string errMsg = "ERROR: ";
const std::string doubleSpace = " ";
const std::string oneSpace = " ";
const std::string doubleAster = "**";
const float lowProb = 0.1f;
/**
* @struct MatrixDims
* @brief Matrix dimensions container
*/
typedef struct MatrixDims
{
int rows, cols;
} MatrixDims;
class Matrix
{
private:
MatrixDims m_Dims;
float *m_Entries;
void initEntries();
void initCopy(const Matrix &m);
public:
Matrix(int rows = 1, int cols = 1);
Matrix(const Matrix &m);
~Matrix();
int getRows() const;
int getCols() const;
Matrix &vectorize();
void plainPrint() const;
Matrix &operator=(const Matrix &other);
Matrix operator*(const Matrix &m) const;
Matrix operator*(const float &m) const;
Matrix operator+(const Matrix &m) const;
Matrix &operator+=(const Matrix &m);
float &operator()(int i, int j);
float operator()(int i, int j) const;
float &operator[](int i);
float operator[](int i) const;
friend std::istream &operator>>(std::istream &s, const Matrix &m);
friend std::ostream &operator<<(std::ostream &s, const Matrix &m);
friend Matrix operator*(const float &c, const Matrix &matrix);
};
std::istream &operator>>(std::istream &s, const Matrix &m);
std::ostream &operator<<(std::ostream &s, const Matrix &m);
Matrix operator*(const float &c, const Matrix &matrix);
#endif //MATRIX_H