C++将 toString 替换为重载的输出运算符

C++ replace toString with an overloaded output operator

本文关键字:输出 运算符 重载 toString 替换 C++      更新时间:2023-10-16

所以我需要将格式化的输出方法(toString)替换为重载的输出/插入运算符,并修改驱动程序以使用重载运算符。

string Movie::toString() const {
ostringstream oS;
oS << "nn====================== Movie Informationn"
<< "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 << "nn====================== Movie Informationn"
<< "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 <<"nt US to World Ratio:t" << (m->getUSBoxOffice()*100.0) / m->getWorldBoxOffice() << "%n" << endl;
    }
    else cout << "Zero World Box Officen";
} 

cout << *m应该可以解决问题。不过,您的operator <<不正确。这应该是friend function.

class Movie {
    friend std::ostream& operator << (std::ostream& os, const Movie &movie);
};
std::ostream& operator << (std::ostream& os, const Movie &movie) { ..... }

替换:

cout << m->toString();

跟:

cout << *m;

简单地说:

cout << *m;

即您必须删除->toString();并引用m(使用 * )。