【问题标题】:undefined reference and operator << vs me未定义的引用和运算符 << vs me
【发布时间】:2018-09-21 14:38:52
【问题描述】:

我正在尝试在我的代码中使用运算符 运算符& 这是我的代码

#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;
}

我该如何处理这个问题?

【问题讨论】:

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


【解决方案1】:

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

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

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

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

这也将使该运算符与临时对象等一起使用,而临时对象等不会与非 const 引用一起使用。

【讨论】:

    【解决方案2】:

    这是因为你在声明之前使用了operator&lt;&lt;(std::ostream&amp;, matrix&amp;)。

    可能的解决方案:

    • 在 main 之前添加前向声明。
    • 将定义移到 main 之前。

    BUT 作为输出运算符与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;
        }
    };
    

    【讨论】:

      猜你喜欢
      • 2012-06-24
      • 2018-09-17
      • 1970-01-01
      • 1970-01-01
      • 2013-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多