对运算符的未定义引用>>结果LINK2019

时间:2018-01-28 19:03:33

标签: c++ operator-overloading

我已经超载了operator>>来读取文件,如下所示:

matrix.h

class Matrix {
   // member functions
};
// declared outside the class
std::istream& operator>>(std::istream& is, const Matrix& rhs);

matrix.cpp

std::istream& operator>>(std::istream& is, Matrix& rhs)
{
    std::string line;
    std::istringstream iss;

    std::getline(is, line); // grab first line
    iss.str(line);

    // Follows:
    //  http://http://en.cppreference.com/w/cpp/container/vector/vector
    //  http://en.cppreference.com/w/cpp/iterator/istream_iterator
    // Avoids:
    //  https://en.wikipedia.org/wiki/Most_vexing_parse
    std::vector<int> dim( (std::istream_iterator<int>(iss)),
                           std::istream_iterator<int>() );

    rhs.setRows(dim[0]);
    rhs.setCols(dim[1]);

    int curr_r = 0;
    while (std::getline(is, line))
    {
        iss.str(line);
        std::vector<double> row( (std::istream_iterator<int>(iss)),
                                  std::istream_iterator<int>() );
        rhs.insRow(curr_r, row);
        curr_r++;
    }
    return is;
}

的main.cpp

#include "matrix.h"
#include <fstream>
#include <iostream>

int main(int argc, char ** argv)
{
    ifstream inf(argv[1]);
    Matrix M;
    while (inf >> M) {}
    return 0;
}

我按照this SO帖子在课外宣布。使用VS2017我收到LINK2019错误,当我尝试编译时,我得到:

undefined reference to `operator>>(std::istream&, Matrix const&)'
collect2: error: ld returned 1 exit status

我以为我有适当的声明/定义我的operator>>重载。想法?

1 个答案:

答案 0 :(得分:2)

undefined reference to `operator>>(std::istream&, Matrix const&)'

没有定义具有Matrix const &参数的运算符。

由于您为const Matrix &声明了运算符,因此您必须为const Matrix & 定义,而不是

std::istream& operator>>(std::istream& is, Matrix& rhs)
{
 . . . 
}

只需添加const:

std::istream& operator>>(std::istream& is,const Matrix& rhs)
{
 . . . 
}