所以我需要用重载的输出/插入操作符替换格式化的输出方法(toString),并修改驱动程序以使用重载操作符。C++用重载输出操作符替换toString
string Movie::toString() const {
ostringstream oS;
oS << "\n\n====================== Movie Information\n"
<< "\n Movie Title:\t" << title << " (" << releaseYear << ")"
<< "\n US Rank & Box Office:\t" << usRank << "\t$" << usBoxOffice
<< "\nNon-US Rank & Box Office:\t" << nonUSRank << "\t$" << nonUSBoxOffice
<< "\n World Rank & Box Office:\t" << worldRank << "\t$" << worldBoxOffice
<< "\n";
return oS.str();
}
,我做这个
std::ostream& operator << (std::ostream& os, const Movie movie)
{
os << "\n\n====================== Movie Information\n"
<< "\n Movie Title:\t" << movie.getTitle()
<< " (" << movie.getReleaseYear() << ") " << movie.getStudio()
<< "\n US Rank & Box Office:\t" << movie.getUSRank() << "\t$" << movie.getUSBoxOffice()
<< "\nNon-US Rank & Box Office:\t" << movie.getNonUSRank() << "\t$" << movie.getNonUSBoxOffice()
<< "\n World Rank & Box Office:\t" << movie.getWorldRank()<< "\t$" << movie.getWorldBoxOffice()
<< "\n";
return os;
}
}
但现在我必须从我的主要(代替的toString)访问该功能,我该怎么办?
const Movie * m;
if(m != nullptr)
{
cout<< m->toString();
if(m->getWorldBoxOffice() > 0)
{
//cout << setprecision(1) << fixed;
cout <<"\n\t US to World Ratio:\t" << (m->getUSBoxOffice()*100.0)/m->getWorldBoxOffice() << "%\n" << endl;
}
else cout << "Zero World Box Office\n";
}
路过常引用:使用'const的电影和movie'(注意**'&'**)。 –