gpt4 book ai didi

2个矩阵的C++乘法

转载 作者:行者123 更新时间:2023-11-28 04:46:58 31 4
gpt4 key购买 nike

我正在尝试将 2 个矩阵与重载的 * 运算符相乘并打印结果。虽然看起来我不能为重载函数提供超过 1 个参数。如何将这两个矩阵传递给重载函数?请在下面查看我的实现。

#include <iostream>
#include<string>
#include <vector>
using namespace std;



class Class1
{
public:
vector<vector<int> > matrix;
vector<vector<int> > tmp;
Class1(vector<vector<int> > p):matrix(move(p)){}

//This function is used to perform the multiplication operation between two square matrices
void operator*(const Class1 &mat1,const Class1 &mat2)
{

for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
{
// matrix[i][j]=0;
for(int k=0;k<4;k++)
{
tmp[i][j]=tmp[i][j]+(mat2.matrix[i][k]*mat1.matrix[k][j]);
}
}
}
// return tmp;
}

void PrintVector()
{
for(int i=0;i<4;i++)
{

for(int j=0;j<4;j++)
{
cout<<tmp[i][j]<<" ";
}
cout<<endl;
}
cout<<endl;
}

};

int main()
{
Class1 Matrix1 = {{{ 21, 12, 13, 14 },
{ 5, 6, 6, 8 },
{ 9, 8, 7, 6 },
{ 3, 2, 1, 1 } }};

Class1 Matrix2 = Matrix1;


Class1 Matrix3 = Matrix1 * Matrix2;

Matrix3.PrintVector();

return 0;
}

最佳答案

1.您正在执行此操作:

Class1 Matrix3 = Matrix1 * Matrix2;

operator*返回类型Class1,不是void。

2.重载运算符时,第一个操作数是 this,第二个操作数是传递给重载运算符函数的参数。因此,您的定义应该是:

  Class1 operator*(const Class1 &mat2)

现在,您可以执行两个对象的乘法运算,并返回一个包含结果的 Class1 类型的新对象。所以,你得到:

 Class1 operator*(const Class1 &mat2)
{
// Creating a reference for the `this` object to minimize changes in code
Class1& mat1 = this;

// perform the multiplication between mat1 and mat2
for ( ... )
.......

// return the newly created object
return tmp;

}

关于2个矩阵的C++乘法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49092037/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com