【发布时间】:2017-10-28 09:09:54
【问题描述】:
类:
#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 的未定义符号: “operator&, Matrix&)”,引用自: main.o 中的 _main ld:未找到架构 x86_64 的符号 clang:错误:链接器命令失败,退出代码为 1(使用 -v 查看调用)
【问题讨论】:
-
在构建时将完整且完整的输出复制为文本,然后编辑您的问题以显示它。请花点时间read about how to ask good questions,并学习如何创建Minimal, Complete, and Verifiable Example。
-
输出操作符签名应该是
ostream& operator <<(ostream& cout, const Matrix & m);将参数命名为cout也不是一个好主意。如何解决您应该阅读的链接器错误this。 -
复制错误。将其粘贴到您的问题中。将其放在
>后面有4 个额外空格的引号中。哦,你有两个>>实现;不知道这是转录错误还是什么。 -
也永远不要在头文件中使用
using namespace std;!这是bad practice in general,但在头文件中更糟。 -
不要使用 new,不要使用指向数组的指针数组。只需使用
std::vector<float> grid(row*column)。