我正在尝试执行此代码,该代码重载*运算符以将2个矩阵Matrix 1和Matrix 2相乘并将其存储在Matrix 3中。我可以使用PrintVector()函数打印矩阵,尽管代码到达时重载函数(它打印"到达此处"语句成功)我得到一个分段错误。一直试图弄清楚这一点,我看不出有什么不对。
#include <iostream>
#include<string>
#include <vector>
using namespace std;
class Class1
{
public:
vector<vector<int> > matrix;
Class1(vector<vector<int> > p):matrix(move(p)){}
//This function is used to perform the multiplication operation between two square matrices
Class1 operator*(const Class1 &mat1)
{
int count = 0;
vector<vector<int> > tmp;
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
{
tmp[i][j]=0;
for(int k=0;k<4;k++)
{
cout<<count++<<endl;
tmp[i][j]=tmp[i][j]+(matrix[i][k]*mat1.matrix[k][j]);
cout<<tmp[i][j]<<" ";
}
}
}
return tmp;
}
void PrintVector()
{
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
{
cout<<matrix[i][j]<<" ";
}
cout<<endl;
}
cout<<endl;
}
};
int main()
{
Class1 Matrix1 = {{{ 1, 2, 3, 4 },
{ 5, 6, 6, 8 },
{ 9, 8, 7, 6 },
{ 3, 2, 1, 1 } }};
Class1 Matrix2 = Matrix1;
cout<<"Reached here"<<endl;
Class1 Matrix3 = Matrix1 * Matrix2;
Matrix3.PrintVector();
return 0;
}
答案 0 :(得分:-1)
好的,所以我需要做的就是调整tmp。谢谢@Igor Tandetnik
#include <iostream>
#include<string>
#include <vector>
using namespace std;
class Class1
{
public:
vector<vector<int> > matrix;
Class1(vector<vector<int> > p):matrix(move(p)){}
//This function is used to perform the multiplication operation between two square matrices
Class1 operator*(const Class1 &mat1)
{
int count = 0;
vector<vector<int> > tmp;
tmp.resize(4);
for(int t=0;t<4;t++)
tmp[t].resize(4);
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
{
tmp[i][j]=0;
for(int k=0;k<4;k++)
{
cout<<count++<<endl;
tmp[i][j]=tmp[i][j]+(matrix[i][k]*mat1.matrix[k][j]);
cout<<tmp[i][j]<<" ";
}
}
}
return tmp;
}
void PrintVector()
{
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
{
cout<<matrix[i][j]<<" ";
}
cout<<endl;
}
cout<<endl;
}
};
int main()
{
Class1 Matrix1 = {{{ 1, 2, 3, 4 },
{ 5, 6, 6, 8 },
{ 9, 8, 7, 6 },
{ 3, 2, 1, 1 } }};
Class1 Matrix2 = Matrix1;
cout<<"Reached here"<<endl;
Class1 Matrix3 = Matrix1 * Matrix2;
Matrix3.PrintVector();
return 0;
}