Can someone find the syntax error in this program - c++

I have written a c++ program to check whether a matrix is sparse or not. The syntax errors which come up are as follows:
main.cpp:56:8: error: deduced class type ‘matrix’ in function return type
matrix matrix <T>::add(matrix r)
^~~~~~~~~~
main.cpp:11:7: note: ‘template class matrix’ declared here
class matrix
^~~~~~
main.cpp:56:8: error: prototype for ‘matrix matrix::add(matrix)’ does not match any in class ‘matrix’
matrix matrix <T>::add(matrix r)
^~~~~~~~~~
main.cpp:19:9: error: candidate is: matrix matrix::add(matrix&)
matrix add(matrix&);
^~~*
And the program is:
#include<iostream>
#include <exception>
using namespace std;
class mismatchDimension:public exception
{
public:
void error_Msg () const;
};
template < class T >
class matrix
{
int row;
int col;
T ele[10][10];
public:
void get ();
bool check_Sparse ();
matrix add (matrix &);
void print ();
};
//no changes to be made to the above code
void mismatchDimension::error_Msg () const const //Error printing method
{
cout << "Dimension of matrices do not match" << endl;
}
template < class T >
void matrix < T >::get () //Element input of matrix
{
cin >> row;
cin >> col;
int i, j;
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
cin >> ele[j][i];
}
}
template < class T >
bool matrix < T >::check_Sparse () //Check if the matrix is sparse
{
int i, j, t;
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
if (ele[j][i] == 0) ++t;
}
}
if (t > (row * col) / 2) return true;
else return false;
}
template < class T >
matrix matrix < T >::add (matrix r) //Addition of the matrices
{
mismatchDimension z;
int i, j;
matrix < T > w;
if (row != r.row && col != r.col) throw z;
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
w.ele[j][i] = ele[j][i] + r.ele[j][i];
}
}
return w;
}
template < class T >
void matrix < T >::print () //printing the matrix
{
int i, j;
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++) cout << ele[j][i] << endl;
}
}
// no changes to be made below
int
main ()
{
matrix < int >m1, m2, m3;
m1.get ();
m2.get ();
try
{
m3 = m1.add (m2);
m3.print ();
} catch (mismatchDimension & m)
{
m.error_Msg ();
}
if (m1.check_Sparse ())
cout << "Matrix is sparse" << endl;
else
cout << "Matrix is not sparse" << endl;
}

There are multiple issues:
In the declaration matrix add (matrix &); you pass by reference while in the definition matrix matrix < T >::add (matrix r) you pass by value. Choose only one.
The return type specification and the parameter type should be provided with template argument:
template <class T>
matrix<T> matrix<T>::add (matrix r)
{
...
}
Note that since C++11, you can also omit template argument in the return type with trailing return type declaration:
template <class T>
auto matrix<T>::add (matrix r) -> matrix
{
...
}

Related

I keep getting the errors no match for 'operator[]', 'A', 'J' and 'N' were not declared in my code. what is the problem with it? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 months ago.
Improve this question
This is the code for my matrix class
The goal here was to Complete the member functions 'void Matrix::add(const Matrix &), void Matrix::mul(double),
void Matrix::mul(const Matrix &), void Matrix::tr(void), and void Matrix::eye(int)'
of the Matrix class in the header file file matrix class
but as soon as I completed that my code started giving me errors and will not run. I am not sure what the problem is.
#ifndef MATRIX_H_
#define MATRIX_H_
#include <iostream>
#include <iomanip>
#include <sstream>
using namespace std;
#define ROW_MAX 10
#define COL_MAX 10
// In the following, the matrix object is referred to as A,
// upper case letters denote matrices,
// and lover case letters denote scalars.
class Matrix
{
public:
Matrix(int m_, int n_, double v_) : m(m_), n(n_) { fill(v_); }; // constructor for an m_ x n_ matrix A initialized to v_
Matrix(int m_, int n_) : Matrix(m_, n_, 0.0) {} // constructor for an m_ x n_ matrix A initialized to 0.0
Matrix(int m_) : Matrix(m_, m_) {} // constructor for an m_ x m_ matrix A initialized to 0.0
Matrix() : Matrix(0) {} // constructor for a 0 x 0 matrix A (empty matrix)
Matrix(const Matrix &A_) { set(A_); } // copy constructor
void from_str(const string &str_); // reads in m, n, and the matrix elements from the string str_ in the format of "m n A[0][0] A[0][1]...A[m-1][n-1]"
string to_str(void); // returns the string representation of A in the format of "m n A[0][0] A[0][1]...A[m-1][n-1]"
int getRows(void) const; // returns the number of rows
int getCols(void) const; // returns the number of columns
double get(int i_, int j_) const; // returns A[i_][j_]
void set(int i_, int j_, double v_); // sets A[i_][j_] to v_ (A[i_][j_] = v_)
void set(const Matrix &A_); // sets A to A_ (A = A_)
void add(const Matrix &A_); // adds A_ to A (A := A + A_)
void mul(double v_); // multiplies A by the scalar v_ (A := v_ A)
void mul(const Matrix &A_); // multiplies A by A_ (A := A A_)
void tr(void); // sets A to its transpose (A := A^T)
void eye(int m_); // sets A to the m_ x m_ identity matrix (A := I)
private:
int m; // the number of rows
int n; // the number of cols
void setRows(int m_); // sets the number of rows to m_
void setCols(int n_); // sets the number of columns to n_
double data[ROW_MAX][COL_MAX]; // holds the matrix data as 2D array
void fill(double v_); // fills the matrix with v_
};
void Matrix::fill(double v_)
{
for (int i = 0; i < getRows(); i++)
{
for (int j = 0; j < getCols(); j++)
{
set(i, j, v_);
}
}
}
void Matrix::from_str(const string &str_)
{
istringstream stream(str_);
int m_ = 0, n_ = 0;
stream >> m_;
stream >> n_;
setRows(m_);
setCols(n_);
int i = 0, j = 0;
double v_;
while (stream >> v_)
{
set(i, j, v_);
j += 1;
if (j == getCols())
{
i = i + 1;
j = 0;
}
if (i == getRows())
{
break;
}
}
}
string Matrix::to_str(void)
{
ostringstream _stream("");
_stream << getRows() << " " << getCols();
for (int i = 0; i < getRows(); i++)
{
for (int j = 0; j < getCols(); j++)
{
_stream << " " << fixed << defaultfloat << get(i, j);
}
}
return _stream.str();
}
int Matrix::getRows(void) const
{
return m;
}
int Matrix::getCols(void) const
{
return n;
}
void Matrix::setRows(int m_)
{
m = m_;
}
void Matrix::setCols(int n_)
{
n = n_;
}
double Matrix::get(int i_, int j_) const
{
return data[i_][j_];
}
void Matrix::set(int i_, int j_, double v_)
{
data[i_][j_] = v_;
}
void Matrix::set(const Matrix &A_)
{
setRows(A_.getRows());
setCols(A_.getCols());
for (int i = 0; i < getRows(); i++)
{
for (int j = 0; j < getCols(); j++)
{
set(i, j, A_.get(i, j));
}
}
}
void Matrix::add(const Matrix &A_)
{
int r = getRows();
int c = getCols();
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
{
A_[i][j] = A_[i][j] + A_[i][j];
}
}
}
void Matrix::mul(double v_)
{
int r = getRows();
int c = getCols();
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
{
A[i][j] = v_ * A[i][j];
}
}
}
void Matrix::mul(const Matrix &A_)
{
int r = getRows();
int c = getCols();
int result[r][c];
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
{
result[i][j] = 0;
for (int k = 0; k < r; k++)
{
result[i][j] += A[i][k] * A_[k][j];
}
}
}
}
void Matrix::tr(void)
{
int r = getRows();
int c = getCols();
int result[r][c];
for (int i = 0; i < N; i++)
{
for (intj = 0; j < N; j++)
{
result[i][j] = A[j][i];
}
}
}
void Matrix::eye(int m_)
{
int r = getRows();
int c = getCols();
for (int row = 0; row < m_; row++)
{
for (int col = 0; col < m_; col++)
{
if (row == col)
A[row][col] = 1;
else
A[row][col] = 0;
}
}
}
#endif
There's quite a few problems in your code. For example, in 'add', you have the following:
A_[i][j] = A_[i][j] + A_[i][j];
However, A_ is const, so you can't be modifying its data. Further, the Matrix class does not have an operator[], so you can't use A_[i] in the first place. You likely want the following:
data[i][j] = A_.data[i][j] + A_.data[i][j];
In your mul(double v_) function, you have the following line:
A[i][j] = v_ * A[i][j];
Again, there is no operator[] for your matrix, so it's not valid. Further, this function does not even have an A defined. You want to deal with the data directly.
data[i][j] = v_ * data[i][j];
In the mul(const Matrix &A_) you again have similar issues with using [], and again you have an A instead of A_. There's other issues in this function, such as not using the result after you've done the calculations.
In the tr function, you have intj instead of int j, and you're using a variable N which is not defined.
The function eye references the variable A which, again, never defined. You want data.
Using an IDE, or even an online compiler like godbolt, points out exactly where every one of these errors are. You can see here a fixed version of the code, though this doesn't fix any logic errors, just the syntax ones.

C++ increment operator overload as friend function not working?

I'm just going to preface this with the fact that I'm new to C++ so it's quite possible there's just a stupid error here, but I can't find it.
I'm just trying to overload the increment operator in a friend function. Everything compiles perfectly and everything works if I explicitly call the postfix increment overload:
operator++(*test, 0);
Every element in the matrix is incremented and the program prints it out using cout perfectly. The problem is when I try to do the normal ++ increment test++; it appears as though something wrong happens with the test pointer to where when it tries to print the test object it doesn't print anything.
Any idea what's going on? I'm clueless. Here's the code I'm working with...
Compile & Run
g++ -o App App.cpp Matrix.cpp
./App
App.cpp
#include <iostream>
#include "Matrix.h"
using namespace std;
#define X 9
int main(int argc, char *argv[])
{
// Start the actual program here
Matrix* test = new Matrix(3,3);
// Row 1
test->setElement(0,0,1);
test->setElement(0,1,2);
test->setElement(0,2,3);
// Row 2
test->setElement(1,0,4);
test->setElement(1,1,5);
test->setElement(1,2,6);
// Row 3
test->setElement(2,0,7);
test->setElement(2,1,8);
test->setElement(2,2,9);
operator++(*test, 0);
//test++;
//++test;
// Print the Matrix object
cout << *test << endl;
}
Matrix.h
#ifndef MATRIX_H
#define MATRIX_H
#include <iostream>
using namespace std;
class Matrix {
friend ostream& operator<<(ostream&, const Matrix&);
friend Matrix& operator++(Matrix&); // prefix increment
friend Matrix& operator++(Matrix&, int); // postfix increment
private:
int rows;
int cols;
int** elements;
public:
// Constructors
Matrix(int);
Matrix(int,int);
Matrix(const Matrix&);
// Define setters
void setElement(int,int,int);
// Define getters
int getRowCount();
int getColCount();
int getElementAt(int,int);
void increment();
// Destructor
~Matrix();
};
#endif
Matrix.cpp
#include <iostream>
#include "Matrix.h"
using namespace std;
//===================================
// DEFINE [CON]/[DE]STRUCTORS
//===================================
// Constructor for creating square matricies
Matrix::Matrix(int _size) {
rows = _size;
cols = _size;
elements = new int*[_size];
for (int i = 0; i < _size; i++) {
elements[i] = new int[_size];
}
}
// Constructor for supporting non-square matricies
Matrix::Matrix(int _rows, int _cols) {
rows = _rows;
cols = _cols;
elements = new int*[_rows];
for (int i = 0; i < _rows; i++) {
elements[i] = new int[_cols];
}
}
// Copy constructor
Matrix::Matrix(const Matrix& mat1) {
Matrix(mat1.rows, mat1.cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
elements[i][j] = mat1.elements[i][j];
}
}
}
// Destructor
Matrix::~Matrix() {
for (int i = 0; i < rows; i++) {
delete[] elements[i];
}
delete[] elements;
}
//===================================
// DEFINE SETTER FUNCTIONS
//===================================
void Matrix::setElement(int row, int col, int newElement) {
if (row > rows-1 || row < 0)
throw "Row out of index";
if (col > cols-1 || col < 0)
throw "Column out of index";
elements[row][col] = newElement;
}
//===================================
// DEFINE GETTER FUNCTIONS
//===================================
int Matrix::getRowCount() { return rows; }
int Matrix::getColCount() { return cols; }
int Matrix::getElementAt(int row, int col) {
if (row > rows-1 || row < 0)
throw "Row out of index";
if (col > cols-1 || col < 0)
throw "Column out of index";
return elements[row][col];
}
//===================================
// OVERRIDE OPERATOR FUNCTIONS
//===================================
// Print the Matrix to the output stream
ostream& operator<<(ostream& out, const Matrix& mat) {
for (int i = 0; i < mat.rows; i++) {
for (int j = 0; j < mat.cols; j++) {
out << mat.elements[i][j] << " ";
}
out << endl;
}
return out;
}
// Prefix. Increment immediately and return the object.
Matrix& operator++(Matrix& mat) {
cout << "Prefix ++ operator" << endl;
// Increment all elements in the object by 1
for (int i = 0; i < mat.rows; i++) {
for (int j = 0; j < mat.cols; j++) {
mat.elements[i][j] += 1;
}
}
return mat;
}
// Postfix. Return the current object and "save" the incremented.
Matrix& operator++(Matrix& mat, int x) {
cout << "Postfix ++ operator" << endl;
// Save the current values
Matrix* curVals = new Matrix(mat);
// Increment the object
++(mat);
// Return the unincremented values
return *curVals;
}
test++ increments the value of test, so that it will point to the memory after your Matrix object. You need to dereference the pointer to get a Matrix object, then apply the increment to that.
What you want is (*test)++ or ++*test.

Weird segmentation fault 11

There are two files:
Matrix.hpp:
template <typename T>
class Matrix {
private:
size_t rows = 0;
size_t cols = 0;
T* data = nullptr;
public:
Matrix() = default;
~Matrix();
Matrix(size_t n, size_t m);
T& operator() (size_t i, size_t j);
};
template <typename T>
Matrix<T>::Matrix(size_t n, size_t m) : rows(n), cols(m) {
try {
data = new T[rows*cols];
} catch (const std::bad_alloc& e) {
std::exit(EXIT_FAILURE);
}
};
template <typename T>
Matrix<T>::~Matrix() {
delete[] data;
}
template <typename T>
T& Matrix<T>::operator()(size_t i, size_t j) {
if (i < rows && i >= 0 && j < cols && j >= 0) {
return data[(i+1)*cols + (j+1)];
} else {
throw std::logic_error("matrix indices out of range");
}
}
and
Main.cpp:
#include <iostream>
#include "Matrix.hpp"
int main() {
size_t n, k;
std::cin >> n >> k;
Matrix<long double> m = {n, k};
for (size_t i = 0; i < m.getNumRows(); ++i) {
for (size_t j = 0; j < m.getNumCols(); ++j) {
std::cin >> m(i,j);
}
}
for (size_t i = 0; i < m.getNumRows(); ++i) {
std::cout << "\n";
for (size_t j = 0; j < m.getNumCols(); ++j) {
std::cout << m(i, j) << " ";
}
}
return 0;
}
When I'm entering something like:
1 2 3 4
I can get
3 4
as answer but sometimes the same input causes Segmentation fault 11 moreover when I'm changing template argument from long double to int, error disappears. How can I fix it?
Your operator function is accessing data outside its bounds.
Passing (0,0) to the function should return data[0]. Currently it returns data[2].
Change line
return data[(i+1)*cols+(j+1)];
to
return data[i*cols+j];

_ASSERTE(_BLOCK_TYPE_IS_VALID(pHead->nBlockUse)) error

I'm trying to figure out why my program fails when I run. So far when I run my program it fails on me. I debugged the error and it brings me to dbgdel.cpp. Line 32 " _ASSERTE(_BLOCK_TYPE_IS_VALID(pHead->nBlockUse));". I've searched for the answer to no avail, but it has something to do with my memory leak?
Here is my header:
#include <iostream>
using namespace std;
namespace project
{
#ifndef MATRIX_H
#define MATRIX_H
typedef int* IntArrayPtr;
class Matrix
{
public:
friend ostream& operator<<(ostream& out, Matrix& object);
//friend istream& operator>>(istream& in, Matrix& theArray);
//Default Constructor
Matrix();
Matrix(int max_number_rows, int max_number_cols, int intial_value);
//Destructor
~Matrix();
//Copy Constructor
Matrix(const Matrix& right_side);
//Assignment Operator
Matrix& operator=(const Matrix& right_side);
void Clear();
int Rows();
int Columns();
bool GetCell(int x,int y, int& val);
bool SetCell(int x,int y, int val);
int getNumber(int r, int c);
//void Debug(ostream& out);
private:
int initialVal;
int rows;
int cols;
IntArrayPtr *m;
};
#endif
}
My implementation file:
#include <iostream>
#include "Matrix.h"
using namespace project;
using namespace std;
namespace project
{
Matrix::Matrix()
{
typedef int* IntArrayPtr;
IntArrayPtr *m = new IntArrayPtr[1];
for(int i = 0; i < 1; i++)
m[i] = new int[1];
for(int r = 0; r < 1; r++)
for(int c = 0; c < 1;c++)
m[r][c] = 0;
}
Matrix::Matrix(int max_number_rows, int max_number_cols, int initial_value)
{
initialVal = initial_value;
rows = max_number_rows;
cols = max_number_cols;
IntArrayPtr *m = new IntArrayPtr[rows];
for(int i = 0; i < rows; i++)
m[i] = new int[cols];
for(int r = 0; r < max_number_rows; r++)
for(int c = 0; c < max_number_cols;c++)
m[r][c] = initial_value;
}
Matrix::~Matrix()
{
for(int i = 0; i <= rows; i++)
delete [] m[i];
delete [] m;
}
void Matrix::Clear()
{
for(int r = 0; r < rows; r++)
for(int c = 0; c < cols;c++)
m[r][c] = initialVal;
}
int Matrix::Rows()
{
return rows;
}
int Matrix::Columns()
{
return cols;
}
bool Matrix::GetCell(int x,int y, int& val)
{
if(x < rows || y < cols)
return false;
else
{
val = m[x - 1][y - 1];
return true;
}
}
bool Matrix::SetCell(int x, int y, int val)
{
if(x < rows || y < cols)
return false;
else
{
m[x - 1][y - 1] = val;
return true;
}
}
int Matrix::getNumber(int r, int c)
{
return m[r][c];
}
ostream& operator<<(ostream& out, Matrix& object)
{
for(int r = 0; r < object.rows; r++)
{
for(int c = 0; c < object.cols; c++)
{
out << " " << object.m[r][c];
}
out << endl;
}
return out;
}
Matrix& Matrix::operator=(const Matrix& right_side)
{
if (this != &right_side)
{
rows = right_side.rows;
cols = right_side.cols;
delete[] m;
IntArrayPtr *m = new IntArrayPtr[rows];
for(int i = 0; i < rows; i++)
m[i] = new int[cols];
for(int r = 0; r < rows; r++)
for(int c = 0; c < cols;c++)
m[r][c] = right_side.initialVal;
}
return *this;
}
/*
void Matrix::Debug(ostream& out)
{
out << "Number of rows = " << rows << endl;
out << "Number of columns = " << cols << endl;
out << "Initializer = " << initialVal << endl;
out << "Current contents of the matrix: " << endl;
out << m << endl;
}
*/
/*
istream& operator >>(istream& in, Matrix& theArray)
{
in >>
}
void interfaceMatrix()
{
int userChoice, rows, columns, value;
cout << "Default matrix or custom(1 for default, 0 for custom): ";
cin >> userChoice;
if (userChoice == 1)
{
Matrix object;
return object;
}
else if(userChoice == 0)
{
cout << "Enter number of rows: ";
cin >> rows;
cout << "Enter number of columns: ";
cin >> columns;
cout << "Enter initial value of each element: ";
cin >> value;
if(rows <= 0 || columns <= 0)
{
cout << "Invalid input." << endl;
exit(1);
}
else
{
Matrix object(rows, columns, value);
return object;
}
}
else
{
cout << "Invalid choice." << endl;
exit(1);
}
}
*/
}
In my driver I just put Matrix test(2,2,2), so I can create a 2 x 2 array with initial value of 2 for each element. I get the above error.
You are allocating rows number of rows, but deallocating rows+1 number of rows.
Check the destructor. <= must be <.
Besides this there are a lot of other [potential] errors in your code:
you are setting the local m variable instead of setting the m data member of your class (that's why I have the convention to always precede data members by m_ to prevent this kind of confusion). This error appears both in the constructor and the assignment operator.
you use rows to allocate the matrix, but max_number_rows to initialize the matrix. Although it works correctly now, it may lead to errors if row is initialized differently later (e.g. if row is initialized with std::max(max_number_rows,1000). Your code in the assignment operator is better.
your if-test in GetCell and SetCell is incorrect. It should probably be >= instead of <
the assignment operator copies the size of the matrix, but assigns all cells an initialValue. This is not an assignment. This implementation might/will confuse the rest of the code.
the typedef of IntArrayPtr is unnecessary
two issues:
You are not allocating any value into the "m" member of your object, you are allocating into local variables named "m"
you are over deallocating by looping from i=0 to i <= rows, you want i=0 to i < rows

C++ Overloading << operator in Matrix class

I am trying to overload the ostream << operator in my Matrix class, but I keep getting the following error:
Expected constructor, destructor, or type conversion before token &
Matrix::ostream& operator<<(const Matrix& matrix)
{
for (int r = 0; r < matrix.getNumrows(); r++)
{
cout << matrix.getPoint(r, 0);
for (int c = 0; c < matrix.getNumcolumns(); c++)
{
cout << " " << matrix.getPoint(r,c);
}
cout << endl;
}
return stream;
}
This is the rest of my class
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include "Matrix.h"
using namespace std;
Matrix::Matrix()
{
}
Matrix::Matrix(int rows, int cols) {
numRows=rows;
numCols=cols;
//col=new double[cols];
mx=new double*[rows];
for ( int i=0; i < rows; i++ ) {
mx[i] = new double[cols];
// initalize each element of the new row.
for ( int c=0; c < cols; c++ ) {
mx[i][c] = 0.0;
}
}
}
Matrix::Matrix(const Matrix &theMatrix) {
int rows=theMatrix.numRows;
int cols=theMatrix.numCols;
numRows = rows;
numCols = cols;
mx=new double*[rows];
for ( int r=0; r < rows; r++ ) {
mx[r] = new double[cols];
// copy each element of the new row.
for ( int c=0; c < cols; c++ ) {
mx[r][c] = theMatrix.mx[r][c];
}
}
}
void Matrix::setMatrix(string file)
{
/* read the file */
fstream inputStream(file.c_str());
if(inputStream.is_open() )
{
string line;
stringstream ss;
getline(inputStream, line);
ss.clear();
ss.str(line);
ss >> numRows >> numCols;
mx=new double*[numRows];
for ( int i=0; i < numRows; i++ ) {
mx[i] = new double[numCols];
// initalize each element of the new row.
for ( int c=0; c < numCols; c++ ) {
mx[i][c] = 0.0;
}
}
//now loop to get values
for(int row=0; row<numRows; row++)
{
getline(inputStream, line);
ss.clear();
ss.str(line);
//now get every value in the line
for(int col=0; col<numCols; col++)
{
double current;
ss >> current;
mx[row][col] = current;
}//end reading values of row
}//end reading rows
}
//close the file
inputStream.close();
}
int Matrix::getNumrows()
{
return numRows;
}
int Matrix::getNumcolumns()
{
return numCols;
}
void Matrix::printPoint()
{
for ( int r=0; r < numRows; r++ )
{
for ( int c=0; c < numCols; c++ )
{
cout << mx[r][c] << " ";
}
cout << endl;
}
cout << endl;
}
bool Matrix::getIsSquared()
{
if( numRows == numCols )
{
return true;
}
else
{
return false;
}
}
double Matrix::det()
{
double det=0.0;
if(numRows!=numCols)
{
cout << "Number Rows must be same as number Colums\n";
}
if(numRows==2)
{
det=(mx[0][0]*mx[1][1])-(mx[0][1]*mx[1][0]);
}
else
{
for(int i=0 ; i<numCols ; i++)
{
Matrix temp(numRows-1,numCols-1);
for(int j=0 ; j<numRows-1 ; j++)
{
for(int k=0 ; k<numCols-1 ; k++)
{
if(k<i)
temp.mx[j][k]=mx[j+1][k];
else
temp.mx[j][k]=mx[j+1][k+1];
}
}
det+=pow(-1.0,i)*mx[0][i]*temp.det();
}
}
return det;
}
double Matrix::getPoint(int row, int col)
{
return mx[row][col];
}
Matrix Matrix::operator +(const Matrix &right) const
{
Matrix result(numRows,numCols);
if ( right.numRows != numRows || right.numCols != numCols )
{
cout << "\nError while adding matricies, the two must have the same dimentions.\n";
}
else
{
for ( int r=0; r < numRows; r++ )
{
for ( int c=0; c < numCols; c++ )
{
result.mx[r][c] = (this->mx[r][c]) + (right.mx[r][c]);
}
}
}
return result;
}
If you want to overload the ostream operator<< for your class, you need to use either a friend function or a non-member function because the ostream object appears on the left-hand side of the expression (it's written as os << my_matrix).
std::ostream& operator<<(std::ostream& os, const Matrix& matrix) { /* ... */ }
It looks like you are trying to implement it as a member function, but that should actually look like:
std::ostream& Matrix::operator<<(const Matrix& matrix) { /* ... */ }
This won't work because when you implement an operator overload as a member function, the type of the object on the left hand side of the expression is the same as the type of the class of which the overload is a member (so, in this case, you'd have to write my_matrix1 << my_matrix2, which isn't what you want).
Inside of the overload, you shouldn't write to cout directly; you should write to the ostream object that is passed as an argument to the function.
Write it as:
ostream& operator<<(ostream& os, const Matrix& matrix)
{
for (int r = 0; r < matrix.getNumrows(); r++)
{
os << matrix.getPoint(r, 0);
for (int c = 0; c < matrix.getNumcolumns(); c++)
{
os << " " << matrix.getPoint(r,c);
}
os << endl;
}
return os;
}
and it will work. It does not have to be a member function of Matrix.
Just change
Matrix::ostream& operator<<(const Matrix& matrix)
to
std::ostream& operator<< (std::ostream &stream, const Matrix &matrix)
It'll be a stand-alone function .. and should work just fine.