简体   繁体   English

C ++重载>>和<<运算符

[英]C++ overloading >> and << operators

I've been trying to overload the >> and << operators in C++, and I keep getting: 我一直在尝试重载C ++中的>><<运算符,而我不断得到:

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 ; 您的声明具有istreamostream参数和返回类型; but the definitions have ifstream and ofstream . 但是定义有ifstreamofstream

Remove the f s from the definitions and all should be fine. 从定义中删除f s,一切都很好。

The friend declarations are fine as they are (assuming they're inside a class definition); friend声明就可以了(假设它们在类定义中); 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. 但是,如果readwrite是公开的,那么你可能会因为他们将不再需要在这种情况下,优先获得考虑unfriending他们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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