我想在我的代码中使用运算符 << 但我收到了这个错误 运算符&<<(std::ostream&, 矩阵) 这是我的代码
#include <iostream>
#include <iomanip>
#include <cassert>
using namespace std;
// A structure to store a matrix
struct matrix
{
int** data; // Pointer to 2-D array that will simulate matrix
int row, col;
};
void createMatrix (int row, int col, int num[], matrix& mat);
int main()
{
int data1 [] = {1,2,3,4,5,6,7,8};
int data2 [] = {13,233,3,4,5,6};
int data3 [] = {10,100,10,100,10,100,10,100};
matrix mat1, mat2, mat3;
createMatrix (4, 2, data1, mat1);
createMatrix (2, 3, data2, mat2);
createMatrix (4, 2, data3, mat3);
cout<<mat1<<endl;
return 0;
}
ostream& operator<< (ostream& output, matrix& mat)
{
for(int i=0; i<mat.row; i++)
{
for(int j=0; j<mat.col; j++)
{
output<<mat.data[i][j];
}
}
return output;
}
我该如何处理这个问题?
最佳答案
您的运算符是在使用后定义的,因此编译器不知道此时存在这样的运算符。您需要在使用之前移动运算符的定义,或者更好的是在定义或声明 main()
之前和 struct matrix
之后声明它:
ostream& operator<< (ostream& output, matrix& mat);
注意:它应该使用 const 引用,因为您无意修改该对象:
ostream& operator<< (ostream& output, const matrix& mat);
这也将使该运算符与临时对象等一起工作,而不会与非常量引用一起使用。
关于c++ - undefined reference 和运算符 << 对我,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52446057/