简体   繁体   中英

C++ overloading >> and << operators

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 istream and ostream ; but the definitions have ifstream and ofstream .

Remove the f s from the definitions and all should be fine.

The friend declarations are fine as they are (assuming they're inside a class definition); they declare functions in the surrounding namespace. However, if read and write are public, then you might consider unfriending them since they won't need privileged access in that case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM