【问题标题】:Can I pass C++ strings into a method in the style of a stream?我可以将 C++ 字符串传递给流样式的方法吗?
【发布时间】:2009-03-19 22:35:07
【问题描述】:

我想这样做:

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++ string stringstream


    【解决方案1】:

    重新设计您的解决方案。如果您的 c-tor 需要字符串,它应该接受字符串。
    如果您的构造函数接受 const 引用,那么在这种情况和类似情况下也会更好。

    no matching function for call to ‘MyClass(std::basic_ostream <..>&)
    

    错误发生是因为 operator

    dynamic_cast< const std::stringstream& >( s << "hello" << "world" )
    

    但是你的团队负责人可能会因为这段代码解雇你:)

    顺便说一句:

    MyClass mc = MyClass("Some string" << anotherString);
    

    可以改写为

    MyClass mc("Some string" << anotherString);
    

    【讨论】:

    • 谢谢,我不知道简写 init。
    • 使用 const std::string& 你将避免不必要的复制
    【解决方案2】:

    你的编译错误看起来已经包含了

    <iosfwd> 
    

    在你的类的头文件中,但你没有包含

    <sstream> 
    

    在 cxx 文件中。

    【讨论】:

    • 这无济于事,因为 "Some string"
    • 谢谢,这篇文章在我重新构建问题之前是相关的 - 并帮助了很多。
    【解决方案3】:

    我认为您应该查看this 问题以获取有关获得所需行为所需的一些提示。

    这种事情好像有点难。

    【讨论】:

      【解决方案4】:

      MyClass::MyClass(ostream &stream)
      {
          string myString = dynamic_cast<stringstream &>(stream.str());
      }
      
      stringstream s;
      MyClass *mc = new MyClass(s << "Some string" << anotherString);
      

      但这确实是一件可怕的事情。试试这样的:

      class Streamer
      {
      stringstream stream;
      public:
          template <class T>
          Streamer &operator <<(const T &object) { stream << object; return *this;}
          operator string() { return stream.str(); }
      };    
      
      class MyClass
      {
      public:
          MyClass(const string &s) : MyString(s) {}
          string MyString;
      };
      
      int main()
      {
          MyClass myClass(Streamer() << "something" << "world");
          cout << myClass.MyString;
      }
      

      【讨论】:

      • 除非你像我一样强制构建一个字符串流。
      • 是的,我认为这是最明智的做法。当然,他可能也不需要使用 new 创建 MyClass 实例。
      • 这比使用宏更优雅吗?
      • 好点,我的意思是优雅:实施更清晰/更容易。
      • 更清楚的是首先传入一个字符串: MyClass myClass(string("something") + "other thing");
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-03
      • 1970-01-01
      • 2012-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多