【问题标题】:How to convert from type (Class) to std:string?如何从类型(类)转换为 std:string?
【发布时间】:2014-06-19 16:06:56
【问题描述】:

所以我有一个名为 blog[] 的字符串数组,我试图在位置 i 处使用数组中的一个字符串,例如:

outfile << blog[i];

但问题是 blog[i] 是 MicroBlog 类型(MicroBlog 是我正在使用的一个类)

所以我的问题是如何将微博类型转换为字符串类型?

这是我尝试使用 blog[i] 的方法:

bool MicroBlog::SaveBlog(const string filename, const MicroBlog &AnotherMicroBlog)
{

    ofstream outfile;
    outfile.open(filename.c_str());


    num_tweets = AnotherMicroBlog.num_tweets;
    for (int i=0; i < num_tweets; i++)                 
    {


                outfile << blog[i];             
        outfile.close();
        }             




}

【问题讨论】:

  • 你会希望你的微博类有一个 .toString() 函数。
  • 您要将其转换为std::string,还是将其流式传输到outfile
  • 规范的方法是重载运算符stackoverflow.com/questions/1549930/…

标签: c++ string class types std


【解决方案1】:

您必须编写自己的运算符,即toString() 或重载&lt;&lt;

 class Microblog {

     ....

     std::string toString() const { //public
          string ret = all_the_data;
          return ret;
     }
 };

然后outfile &lt;&lt; blog[i].toString();

【讨论】:

  • 所以我把它放在我的 .h 中,然后在我尝试使用 blog[i] 的地方对我的代码做什么?我已经添加了我正在尝试使用的方法。
  • 这个? outfile &lt;&lt; blog[i].toString();?
猜你喜欢
  • 2011-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
  • 2015-11-01
  • 2017-07-15
  • 1970-01-01
相关资源
最近更新 更多