重载运算符<<为字符串工作
在以下代码中:
using namespace 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;
}
重载 operator <<
的正确方法是什么
copy(test.begin(), test.end(), sIt);
工作。
我缺少什么?
编辑:我只是愚蠢......忘记包含“字符串”标题
谢谢!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不需要重载
operator<<
来处理字符串,它已经知道如何处理它们。将产生:
您想在那里做一些不同/特别的事情吗?
You do not need to overload
operator<<
to work with strings, it already knows how to handle them.will produce:
Is there anything different/special that you want to be done there?
正如 David 已经指出的那样,已经有一个用于字符串的
运算符<<
,因此您不必提供一个。如果您真的想定义自己的重载,那么就会有一个小问题,因为实际上您不允许这样做。operator<<
是在std
命名空间中定义的,因此如果您希望为std::string
(中的版本)提供可用的重载,大多数实现都是模板函数,因此存在潜在的重载),您也必须在 std 命名空间中执行此操作(这是因为歧义和重载的方式)已在 C++ 中解决,这里有一些注意事项)。例如:但是,普通用户不允许向
std
命名空间添加内容,因为它可能会产生不可预见的特定于实现的影响,并且可能会破坏标准库内的各种内容。另外,不能保证您的标准库实现具有可重载运算符<<。这意味着,它可能有效,也可能无效。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 thestd
namespace, so if you want to have a usable overload forstd::string
(the version in most implementations is a template function, so there is a potential overload), you'll have to do this in thestd
namespace too (this because of the ways ambiguities and overloads are resolved in C++, there are some caveats here) . For example: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.让我添加 cplusplus.com 的链接以供将来参考
http://www.cplusplus.com /参考/算法/复制/
Lemme just add the link from cplusplus.com for future reference
http://www.cplusplus.com/reference/algorithm/copy/