我可以通过 C++ 将字符串转换成流风格的方法?
我想这样做:
MyClass mc = MyClass("Some string" << anotherString);
感谢您的回答,我决定根据您告诉我的内容重新写这个问题,因为它变得有点混乱。 最终,我阅读了 C++ 格式宏/内联 ostringstream,并决定使用宏,因为使用构造函数实际上不可能做到这一点。 有些答案不再相关。
现在,我实际上可以做的是:
MY_CLASS("Some string" << anotherString << " more string!");
使用这个宏:
#include <sstream>
#define MY_CLASS(stream) \
MyClass( ( dynamic_cast<std::ostringstream &> ( \
std::ostringstream() . seekp( 0, std::ios_base::cur ) << stream ) \
) . str() )
MyClass 构造函数采用一个字符串:
MyClass::MyClass(string s) { /* ... */ }
I'd like to do this:
MyClass mc = MyClass("Some string" << anotherString);
Thanks for your answers, I have decided to re-write this question based on what you've told me, as it's gotten a little messy. Eventually, I read C++ format macro / inline ostringstream, and decided to use a macro, as it's not really possible to do this using a constructor. Some answers my no longer be relevant.
Now, what I can actually, do is:
MY_CLASS("Some string" << anotherString << " more string!");
Using this macro:
#include <sstream>
#define MY_CLASS(stream) \
MyClass( ( dynamic_cast<std::ostringstream &> ( \
std::ostringstream() . seekp( 0, std::ios_base::cur ) << stream ) \
) . str() )
Where the MyClass constructor takes a string:
MyClass::MyClass(string s) { /* ... */ }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
重新设计您的解决方案。 如果您的 c-tor 需要字符串,它应该接受字符串。
同样在这种情况和类似情况下,如果您的构造函数接受 const 引用,效果会更好。
发生错误是因为运算符<< 定义并返回 std::basic_ostream 而不是 std::stringstream 对象。 当然你可以使用
,但你的团队领导可能会因为这段代码解雇你:)
顺便说一句:
可以重写为
redesign your solution. if your c-tor needed string it should accept string.
also in this and similar cases will better if your constructor will accept const reference.
error happened because operator<< defined for and returns std::basic_ostream not std::stringstream object. ofcourse you could use
but your team lead could fire you for this code:)
BTW:
could be rewriten as
您的编译错误看起来已经包含
在类的头文件中,但尚未包含
在 cxx 文件中。
Your compile error looks like have included
in your class's header file, but you haven't included
in the cxx file.
我认为您应该查看这个问题,以获取一些有关获得所需行为所需的提示。
这种事,似乎有点困难。
I think you should look at this question for some hints as to what will be required to get the behavior you want.
This sort of thing seems to a bit difficult.
<< 运算符返回 ostream &,而不是streamstream &,因此您必须进行动态转换:
但这实际上是一件可怕的事情。 尝试这样的事情:
The << operator returns an ostream &, not a streamstream &, so you'd have to do a dynamic cast:
But really that's a terrible thing to do. Try something like this: