Answer the question
In order to leave comments, you need to log in
What should the matrix class method return?
I am writing a square matrix class, here, in fact, the class itself:
#ifndef MATRIX_H
#define MATRIX_H
#include <string.h>
class Matrix
{
private:
std::string name;
double **matrix;
int size;
public:
// Default constructor
Matrix() : name("NaN"), matrix(nullptr), size(0)
{ }
// Constructor with values
Matrix(std::string nm, int sz) : name(nm), size(sz)
{
try
{
matrix = new double *[size];
for(int i = 0; i < size; i++)
matrix[i] = new double[size];
}
catch(std::bad_alloc& ex)
{
std::cerr << ex.what() << std::endl;
}
}
// Arithmetic shit
bool operator== (const Matrix &operand);
bool operator!= (const Matrix &operand);
Matrix operator+(const Matrix &operand);
};
#endif
#include <iostream>
#include "matrix.h"
/* return 1 if ==
return 0 if !=*/
bool Matrix::operator== (const Matrix &operand)
{
if(operand.size != this->size)
return 0;
for(int i = 0; i < this->size; i++)
{
if(this->matrix[i][i] != operand.matrix[i][i])
return 0;
}
return 1;
}
/* return 1 if !=
return 0 if ==*/
bool Matrix::operator!= (const Matrix &operand)
{
if(operand.size != this->size)
return 1;
for(int i = 0; i < this->size; i++)
{
if(this->matrix[i][i] != operand.matrix[i][i])
return 1;
}
return 0;
}
Matrix Matrix::operator+ (const Matrix &operand)
{
const Matrix result;
//pass
}
nullptr
we cannot return.
Answer the question
In order to leave comments, you need to log in
1. There is no destructor in your code that would free memory => you have a potential memory leak.
2. In the case of the addition operator, if the matrices have different sizes, throw an exception through std::runtime_error
3. You do not have a copy constructor and when copying an object, a pointer to the allocated memory will be copied.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question