c++ - undefined reference 和运算符 << 对我

标签 c++ operator-overloading undefined-reference

我想在我的代码中使用运算符 << 但我收到了这个错误 运算符&<<(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/

相关文章:

c++ - STD::string 作为动态分配对象的成员参数

java - 选择元素的所有组合

C++ [ ] 索引运算符重载为访问器和修改器

c++ - 在 C++11 中使用用户定义的转换重载运算符推导

c++ - 为什么模板只能在头文件中实现?

opencv - 在ubuntu 11.10中编译opencv2.3.1

.net - native C++ 应用程序的 list ?

c++ - 代码中没有任何 STL 的 STL 错误

python - 如何根据参数类型重载 __init__ 方法?

c++ - 对C头文件的 undefined reference