I created a template class which named with Matrix. I'm trying to figure out how to implement an operator+ overload for a pointer which is pointed an Matrix object. My object is scalar matrix operations. I want to add an integer value to each cells on the matrix. I could not understand what is going on my code. The templates have confused me a lot.
"m1" is my Matrix object. When I use m1 = m1+2
, I'm getting segmentation fault error.
I have tried many different combinations, but I get the same error all the time.
- I tried without a pointer.
- I tried typing int instead of T.
- Instead of directly returning
new Matrix <int> (10,10,2)
, I tried:
Matrix <int> * m = new Matrix <int> (10,10,2)
return m;
- When I delete second
m1->print();
statement in main function, the "segmentation fault" error disappears, but every time I try to print I get an error again.
My Matrix class:
template <typename T>
class Matrix{
vector< vector<T> > matris;
public:
Matrix(); // 10x10 matrix with zeros
Matrix(int width, int height, int value);
void print();
Matrix* operator+(T value){
return (new Matrix<int>(10,10,2)); // 10x10 matrix filled with 2
}
};
My main function:
int main(){
Matrix <int> *m1 = new Matrix <int>(); // 10x10 matrix with zeros
m1->print(); // it succesfully shows the elements
m1 = m1 + 2; // whenever I tried this, I get "Segmentation Fault"
m1->print();
return 0;
}
My print() function:
template <typename T>
void Matrix<T>::print(){
for(int h=0; h<matris.size(); h++){
for(int w=0; w<matris[0].size(); w++){
printf("%4d", matris[h][w]);
}
cout << endl;
}
}
Output:
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
Segmentation fault
My expectation is that the assignment was successful, but I get the segmentation fault error. What am I doing wrong here?