因此,我需要使用重载的输出/插入运算符替换格式化的输出方法(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";
}

最佳答案

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) { ..... }

关于c++ - C++用重载的输出运算符替换toString,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21801430/

10-12 01:51