c++ - 我可以将 C++ 字符串以流的形式传递给方法吗?

标签 c++ string stringstream

我想这样做:

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/

相关文章:

c - 使用函数将字符串转换为字符

c++ - 避免从字符串流中抓取任何内容

c++ - STL::map erase 与 std::vector erase 的行为不同

c++ - 内联函数作为模板参数,不使用函数指针

c++ - 无法在 C++ 中创建包含日期和时间的文件名

c++ - Variadic 模板函数名称查找无法找到特化

C - 如何在数组中存储带有变量的字符串?

c++ - stringstream->rdbuf()->pubsetbuf 没有设置缓冲区

c++ - 用isalnum拆分字符串并存储到字符串 vector 中

c++ - VBA 调用 C++ DLL - 错误 48(找不到文件)