I’ve been trying to overload the >> and << operators in C++, and I keep getting:
Error 2 error LNK2019: unresolved external symbol "class std::basic_istream<char,struct std::char_traits<char> > & __cdecl operator>>(class std::basic_istream<char,struct std::char_traits<char> > &,class ArrayStorage &)" (??5@YAAAV?$basic_istream@DU?$char_traits@D@std@@@std@@AAV01@AAVArrayStorage@@@Z) referenced in function _main G:\Desktop\ACW\08227_ACW2_TestHarnessSolution\main.obj
The way I’m doing it is:
//.h file
friend ostream& operator<<(ostream &sout, ArrayStorage &Astor);
friend istream& operator>>(istream &sin, ArrayStorage &Astor);
//cpp file
ofstream& operator<< (ofstream &sout, ArrayStorage &astor)
{
astor.write(sout);
return sout;
}
ifstream& operator>> (ifstream &sin, ArrayStorage &astor)
{
astor.read(sin);
return sin;
}
A friend of mine told me to take the “friend” off the declaration in the header file and move it to outside the class, but I still get the same error. It’s probably something easy, but I can’t figure out what’s not working.
Your declarations have parameter and return types of
istreamandostream; but the definitions haveifstreamandofstream.Remove the
fs from the definitions and all should be fine.The
frienddeclarations are fine as they are (assuming they’re inside a class definition); they declare functions in the surrounding namespace. However, ifreadandwriteare public, then you might consider unfriending them since they won’t need privileged access in that case.