开发者

Overloading operator<< to work for string

In the following code:

 using namespac开发者_JAVA百科e std;

 //ostream& operator<< (ostream& out,const string & str)
 //{    
 //  out << str.c_str();    
 //  return out; 
 //}

 int _tmain(int argc, _TCHAR* argv[])
 {

     ofstream file("file.out");  

     vector<string> test(2); 

     test[0] = "str1"; 
     test[1] = "str2";
     ostream_iterator<string> sIt(file);

     copy(test.begin(), test.end(), sIt);

     file.close();
    return 0;
}

what is the proper way to overload operator << to make copy(test.begin(), test.end(), sIt); work.

What am I missing?

EDIT: I'm just stupid... forgot to include "string" header

Thank you!


You do not need to overload operator<< to work with strings, it already knows how to handle them.

std::copy( test.begin(), test.end(), 
           std::ostream_iterator<std::string>( file, "\n" ) );

will produce:

str1
str2

Is there anything different/special that you want to be done there?


As David already pointed out, there is already a operator<< for strings, so you don't have to provide one. Should you really want to define your own overload anyway, then there's a slight problem, because actually you are not allowed to do that. operator<< is defined in the std namespace, so if you want to have a usable overload for std::string (the version in most implementations is a template function, so there is a potential overload), you'll have to do this in the std namespace too (this because of the ways ambiguities and overloads are resolved in C++, there are some caveats here) . For example:

namespace std {
 ostream& operator<< (ostream& out,const string & str)
  {     
    out << "A STRINGY:" << str.c_str();     
    return out; 
  }
}

However, adding stuff into the std namespace is not allowed for ordinary users, because it might have implementation specific effects that are unforeseeable and could break all kinds of stuff inside the standard library. Also, there is no guarantee, that your implementation of the standard library has a overloadable operator<<. This means, it could work or it could not.


Lemme just add the link from cplusplus.com for future reference

http://www.cplusplus.com/reference/algorithm/copy/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜