我创建了一个以Matrix命名的模板类。我试图弄清楚如何为指向Matrix对象的指针实现operator +重载。我的对象是标量矩阵运算。我想为矩阵上的每个单元格添加一个整数值。我不明白我的代码在做什么。模板让我很困惑。
“ m1”是我的Matrix对象。当我使用m1 = m1+2
时,出现分段错误错误。
我尝试了许多不同的组合,但是我总是遇到相同的错误。
new Matrix <int> (10,10,2)
,而是尝试了:Matrix <int> * m = new Matrix <int> (10,10,2)
return m;
m1->print();
语句时,“段错误”错误消失了,但是每次尝试打印时,我都会再次收到错误。我的矩阵类:
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
}
};
我的主要功能:
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;
}
我的print()函数:
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;
}
}
输出:
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
我期望分配成功,但是出现分段错误错误。我在这里错了吗?
使用时
m1 = m1 + 2;
不使用重载的operator+
。那只是指针算法。之后,m1
指向您不拥有的内存。之后访问m1
的成员将导致未定义的行为。
您可以使用来从语法上解决此问题
m1 = *m1 + 2;
但是有其自身的问题。当您这样做时,指向的原始内存m1
将丢失到您的程序中。您有内存泄漏。
提供重载为
Matrix* operator+(T value) { ... }
不是惯用语言。也许您想使用:
Matrix operator+(T const& value) const { ... }
更好的选择是使用几个非成员函数重载:
Matrix operator+(Matrix const& m, T const& value);
Matrix operator+(T const& value, Matrix const& m);
有了它,您可以使用:
Matrix<int> m1;
Matrix<int> m2 = m1 + 10;
Matrix<int> m3 = 30 + m1;
有关操作符重载的更多信息,请参见What are the basic rules and idioms for operator overloading?