pstatix
pstatix

Reputation: 3848

Undefined reference to operator>> results in LINK2019

I've overloaded the operator>> to read from file like so:

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

I declared it outside the class per this SO post. Using VS2017 I am receiving the LINK2019 error and when I try to compile I get:

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

I thought I had appropriate declared/defined my operator>> overload. Thoughts?

Upvotes: 0

Views: 101

Answers (1)

Johan Lundberg
Johan Lundberg

Reputation: 27028

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

There's no defined operator with Matrix const & argument.

Since you declare the operator for const Matrix &, you must define it for const Matrix &, not

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

Just add const:

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

Upvotes: 2

Related Questions