类别:
#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);
Matrix 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的未定义符号: “operator&lt;&lt;(std :: __ 1 :: basic_ostream&gt;&amp;,Matrix&amp;)”,引自: _main在main.o中 ld:找不到架构x86_64的符号 clang:错误:链接器命令失败,退出代码为1(使用-v查看调用)
答案 0 :(得分:0)
您输错误码,更改运算符&gt;&gt;
之一ostream& operator>>(ostream& cout, Matrix & m)
{
m.printMatrix();
return cout;
}
到
ostream& operator<<(ostream& cout, Matrix & m) {
m.printMatrix();
return cout;
}
答案 1 :(得分:0)
还
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];