未定义的引用和运算符<< vs me

时间:2018-09-21 14:38:52

标签: c++ operator-overloading undefined-reference

我正在尝试在代码中使用运算符<<,但出现此错误 operator&<<(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;
}

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

您使用的运算符在使用后定义,因此编译器不知道该运算符当时存在。您需要在使用之前移动运算符的定义,甚至最好在定义或声明main()之前和struct matrix之后声明它:

 ostream& operator<< (ostream& output, matrix& mat);

注意:它应该使用const引用,因为您无意修改该对象:

 ostream& operator<< (ostream& output, const matrix& mat);

这也将使此运算符可以用于临时对象等,而不能用于非const引用。

答案 1 :(得分:0)

这是因为您在声明operator<<(std::ostream&, matrix&)之前就使用它。

可能的解决方案:

  • 在main之前添加一个前向声明。
  • 将定义移至main之前。

但是,因为输出运算符与matrix类紧密耦合,为什么不将其声明为该类的朋友呢?这样,您将明确记录输出运算符与类的紧密耦合。

struct matrix
{
    int** data;       // Pointer to 2-D array that will simulate matrix
    int row, col;

    // Note the output operator should not modify the object.
    // So you can pass it as a const reference in the second parameter.
    friend std::ostream& operator<<(std::ostream& output, matrix const& mat)
    {
        for(int i=0; i < mat.row; ++i)     // prefer prefix increment.
        {
            for(int j=0; j < mat.col; ++j)
            {
                output << mat.data[i][j] << " ";
            }
            output << "\n";
        }
        return output;
    }
};
相关问题