我想这样做:
MyClass mc = MyClass("Some string" << anotherString);
感谢您的回答,我决定根据您告诉我的内容重写这个问题,因为它变得有点困惑。最后,我读了 C++ format macro / inline 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) { /* ... */ }
最佳答案
重新设计您的解决方案。如果你的 c-tor 需要字符串,它应该接受字符串。
如果您的构造函数接受 const 引用,在这种情况和类似情况下也会更好。
no matching function for call to ‘MyClass(std::basic_ostream <..>&)
错误发生是因为 operator<< 定义并返回 std::basic_ostream 而不是 std::stringstream 对象。当然你可以使用
dynamic_cast< const std::stringstream& >( s << "hello" << "world" )
但是你的团队领导可能会因为这个代码而解雇你:)
顺便说一句:
MyClass mc = MyClass("Some string" << anotherString);
可以重写为
MyClass mc("Some string" << anotherString);
关于c++ - 我可以将 C++ 字符串以流的形式传递给方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/664320/