c++ - 如何从模板类中重载创建的指针对象上的运算符?
问题描述
我创建了一个以 Matrix 命名的模板类。我试图弄清楚如何为指向 Matrix 对象的指针实现 operator+ 重载。我的对象是标量矩阵运算。我想为矩阵上的每个单元格添加一个整数值。我无法理解我的代码发生了什么。模板让我很困惑。
“m1”是我的矩阵对象。当我使用m1 = m1+2
时,我收到分段错误错误。
我尝试了许多不同的组合,但我总是遇到同样的错误。
- 我试过没有指针。
- 我尝试输入int而不是T。
- 我没有直接返回
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
指向你不拥有的内存。访问 after 的成员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;
有关运算符重载的更多信息,请参见运算符重载的基本规则和习惯用法是什么?
推荐阅读
- bootstrap-4 - 如何在引导显示中显示“在具有多行标题和标签的两列中
- asp.net-mvc - Fancytree 在 MVC 4 中无法正确加载
- tensorflow2.0 - TensorFlow Lite 全整数量化在 TF 2 中失败
- laravel - 尝试引用关系表中的类型时找不到列
- postgresql - 带有子查询的 SQL 条件返回操作数错误
- swift - 在 SwiftUI 上的 Firebase 中使用 updateData 函数时出错
- git - 有没有办法让 git add --patch 跳过所有单行更改?
- android - Android 应用程序与 Play 商店中的新设备不兼容
- android - UI Automator - 获取 XY 坐标的背景颜色
- javascript - 检查输入值是否为回文的函数总是返回 true