矩阵运算C++运算符重载程序错误

Matrix operations C++ operator overloading program error

本文关键字:重载 程序 错误 运算符 C++ 运算      更新时间:2023-10-16

类别:

#include <string>
using namespace std;
class Matrix{
public:
float **grid;
Matrix(int r, int c);
friend istream& operator >>(istream& cin, Matrix & m );
void setMatrix();
void printMatrix();
friend ostream& operator <<(ostream& cout, Matrix & m);
private:
int row;
int column;
};
istream& operator >>(istream& cin, Matrix & m );
ostream& operator <<(ostream& cout, Matrix & m);

矩阵cpp

#include "Matrix.h"
#include <iostream>
#include <string>
using namespace std;
//First constructor
Matrix::Matrix(int r, int c){
row=r; // Row size
column=c; // Column Size
if(row>0 && column>0)
{
grid = new float*[row]; // Creating 2d dynamic array
for(int i=0; i<row;i++)
grid[row] = new float [column];
//Setting all elements to 0
for(int i=0; i<row; i++)
{
for(int j =0; j<column; j++)
{
grid[i][j]=0;
}

}
}
else{
cout<<"Invalid number of rows or columns!"<<endl;
}

}
//Setting values to the matrix
void Matrix::setMatrix()
{
for(int i=0; i<row; i++)
{
for(int j=0;j<column;j++)
{
cin>>grid[i][j];
}
}
}
//Print matrix
void Matrix::printMatrix()
{
for(int i=0;i<row;i++)
{
for(int j=0; j<column; j++)
{
cout<<grid[i][j]<<" ";
}
cout<<endl;
}
}
//Istream function
istream& operator >>(istream& cin, Matrix & m)
{
m.setMatrix();
return cin;
}
//ostream function
ostream& operator>>(ostream& cout, Matrix & m)
{
m.printMatrix();
return cout;
}

主要功能

#include <iostream>
#include "Matrix.h"
using namespace std;
int main()
{
Matrix m = Matrix(3,2);
cout << m;
return 0;
}

我正在尝试编写一个程序来执行不同的矩阵运算。这段代码应该主要创建一个尺寸为3*2的矩阵,构造函数将其所有值初始化为0,然后打印矩阵。在编译这个时,我得到了一个"链接器命令失败,退出1"错误,我真的不知道如何修复。我怎么能把它修好呢?

错误:

体系结构x86_64的未定义符号:"运算符<<(std::__1::basic_stream>&,矩阵&)",引用自:_main in mainld:找不到体系结构x86_64的符号clang:错误:链接器命令失败,退出代码为1(使用-v查看调用)

您有打字错误,请更改其中一个操作员>>

ostream& operator>>(ostream& cout, Matrix & m)
{
m.printMatrix();
return cout;
}

ostream& operator<<(ostream& cout, Matrix & m) {
m.printMatrix();
return cout;
}

还有

grid = new float*[row]; // Creating 2d dynamic array
for (int i = 0; i<row; i++)
grid[row] = new float[column];

应该是

grid = new float*[row]; // Creating 2d dynamic array
for (int i = 0; i<row; i++)
grid[i] = new float[column];