My homework question was:
Create a matrix class using the template and overload +,-,,/,<<,>>,+=,-=,=,/= operators so they can be used for matrices operations.
I've overloaded the << and >> operators so I can read the matrix elements and print the matrix, and seems to work alright but when I tried to overload the + operator I've got a segmentation fault and I don't know where the problem might be.
Matrix class:
template <class T> class matrice{
int l,c;
vector<vector<T> > matrix;
public:
matrice(){}
~matrice(){}
matrice operator+(matrice altaMatrice){...}
matrice operator-(matrice altaMatrice){...}
matrice operator*(matrice altaMatrice){...}
matrice operator/(matrice altaMatrice){...}
matrice operator+=(matrice altaMatrice){...}
matrice operator-=(matrice altaMatrice){...}
matrice operator*=(matrice aaltaMatrice){...}
matrice operator/=(matrice altaMatrice){...}
friend istream& operator>>(istream& myStream, matrice& altaMatrice){...}
friend ostream& operator<<(ostream& myStream, matrice& altaMatrice){...}
};
- overloading >> and <<:
friend istream& operator>>(istream& myStream, matrice& altaMatrice){
T element;
cout<<"linii si coloane:"<<endl;
cin >> altaMatrice.l;
cin >> altaMatrice.c;
cout<<"elem matrice"<<endl;
for (int i = 0; i < altaMatrice.l; i++) {
vector<T> linie;
for (int j = 0; j < altaMatrice.c; j++) {
cin >> element;
linie.push_back(element);
}
altaMatrice.matrix.push_back(linie);
}
return myStream;
}
friend ostream& operator<<(ostream& myStream, matrice& altaMatrice){
cout << "\n\n";
for (int i = 0; i < altaMatrice.l; i++) {
for (int j = 0; j < altaMatrice.c; j++)
cout << altaMatrice.matrix[i][j] << "\t";
cout << "\n\n";
}
return myStream;
}
- and here is the overloading I have tried and got the segmentation fault:
matrice operator+(matrice altaMatrice){
matrice temp;
for(int i=0; i<altaMatrice.l; i++)
{
for(int j=0; j<altaMatrice.c; j++)
{
temp.matrix[i][j] = this->matrix[i][j] + altaMatrice.matrix[i][j];
}
}
return temp;
}
-PS: I don't know if it helps but this is the main function:
int main(){
matrice<int> A;
cin >> A;
cout << A;
matrice<int> C;
C = A + A;
cout << C;
return 0;
}
- Here is the output without the matrix C, only reading and printing the matrix A:
linii si coloane:
2
2
elem matrice
1
2
3
4
1 2
3 4
Process finished with exit code 0
- the output with the matrix C (A + A):
linii si coloane:
2
2
elem matrice
1
2
3
4
1 2
3 4
Process finished with exit code -1073741819 (0xC0000005)