2014-02-15 27 views
1

所以我需要用重载的输出/插入操作符替换格式化的输出方法(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"; 
} 
+0

路过常引用:使用'const的电影和movie'(注意**'&'**)。 –

回答

3

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

它说“没有操作符<< <<”匹配这些操作数操作数类型是std :: ostream << const Movie“ – FEARxxx

+0

@ user3314023试试我的编辑 – yizzlez

+0

OMG非常感谢你,它的工作原理! – FEARxxx

1

取代:

cout << m->toString(); 

有:

cout << *m; 
+0

糟糕,是的,会编辑。谢谢! –

0

只需像这样:

cout << *m; 

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