重载 std::string 构造函数
我可以重载 std::string 构造函数吗?
我想创建一个接受 std::wstring 并返回 std::string 的构造函数。这可能吗?如何实现?
谢谢。
Can I overload the std::string constructor?
I want to create a constructor which takes std::wstring and return a std::string. is it possible and how?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,它需要更改
std::string
声明。您可以使用转换函数,例如:
但是,您需要决定如何处理无法使用
std::string
的 8 位编码表示的符号:是否将它们转换为多字节符号或抛出异常。请参阅 wcsrtombs 函数。Nope, it would require changing
std::string
declaration.You can have a conversion function instead, like:
However, you need to decide what to do with symbols that can't be represented using 8-bit encoding of
std::string
: whether to convert them to multi-byte symbols or throw an exception. See wcsrtombs function.而是定义一个自由函数:
Rather define a free function:
不可以,您不能向
std::string
添加任何新的构造函数。您可以做的是创建一个独立的转换函数:如果您(认为您)希望这种情况自动发生,我强烈建议重新评估这个想法。您会给自己带来很多麻烦,因为在您最意想不到的时候,
wstring
会自动被视为string
。No, you cannot add any new constructors to
std::string
. What you can do is create a standalone conversion function:If you (think you) want this to happen automatically, I strongly suggest re-evaluating that idea. You'll cause yourself a significant amount of headaches as
wstring
s are automatically treated asstring
when you least expect it.这不是正确的做法,我认为我在编码时吸了一些东西,但它解决了问题。检查最后一个函数“convert_str”。
This is not the Right True Way of doing it, and I think that I had smoked something when I coded this, but it solves the problem. Check the last function, `convert_str'.