2014-05-02 57 views
0

所以我有一個字符串名爲博客[]數組,我想在我的位置使用字符串從數組,如:如何從類型(Class)轉換爲std:string?

outfile << blog[i]; 

但問題是,博客[i]是類型微博(MicroBlog是我正在使用的一類)

所以我的問題是如何從類型MicroBlog轉換爲字符串類型?

這裏是我想利用博客[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(); 
     }    




} 
+0

你會希望你的MicroBlog類有一個.toString()函數。 – pennstatephil

+0

[C++相當於java.toString?]的可能重複(http://stackoverflow.com/questions/1549930/c-equivalent-of-java-tostring) – pennstatephil

+1

是否要將其轉換爲一個'std :: string ',還是你想把它流出到'outfile'? –

回答

1

你必須即寫自己的運營商toString()或過載<<

class Microblog { 

    .... 

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

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

+0

所以我把它放在我的.h,然後我怎麼做我的代碼,我試圖使用博客[我]?我已經添加了我正在嘗試使用的方法。 – user3434233

+0

This? 'outfile << blog [i] .toString();'? – yizzlez

相關問題