Search code examples
c++overloadingoperator-keywordistream

c++ istream operator overloading unresolved


source.h:

#include <iostream>
class date{
public:
std::string str_time;
friend std::istream& operator >> (std::istream& para_stream, date& para_date);
};

source.cpp:

#include "source.h"
std::istream& operator >> (std::istream& para_stream, date& para_date)
{
  istream >> para_date.str_time;
  return istream;
}

ERROR: Error 2 error LNK2019: unresolved external symbol "class std::basic_istream<char,struct std::char_traits > & __cdecl src::operator>>(class std::basic_istream<char,struct std::char_traits > &,class src::date &)" (??5src@@YAAAV?$basic_istream@DU?$char_traits@D@std@@@std@@AAV12@AAVdate@0@@Z) referenced in function "public: bool __thiscall src::DB::del_vouc(int const &)" (?del_vouc@DB@src@@QAE_NABH@Z) C:\Users\Dell\Documents\Visual Studio 2013\Projects\foodstore\foodstore\DB.obj foodstore


Solution

  • The linker is complaining about src::DB having an "unresolved external symbol"

    You have defined a function inside source.cpp, so it remains internal to this file (translation unit).

    If you add a declaration to the header file, like this

    std::istream& operator >> (std::istream& para_stream, date& para_date);
    

    it becomes available externally, rather than "hidden" inside the cpp file.

    Alternatively, you can define (rather than just declare) it in the header file, but it MUST be marked inline otherwise you end up with a definition every time the header is included.