如何从type (Class)转换为std:string

How to convert from type (Class) to std:string?

本文关键字:转换 std string Class type      更新时间:2023-10-16

我有一个名为blog[]的字符串数组我试图使用数组中位置I的字符串,如:

outfile << blog[i];

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

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

这是我试图使用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()或重载<<:

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

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