C++将 toString 替换为重载的输出运算符
C++ replace toString with an overloaded output operator
所以我需要将格式化的输出方法(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
(使用 *
)。
相关文章:
- 尝试重载输出运算符时,我无法遍历对象向量
- 如何为流输出运算符提供重载<<模板'using'类型别名?
- 在C++中重载输入/输出运算符
- 如何处理自定义输出运算符中的 iomanips?
- 基于对函数的参数调用流输出运算符的能力重载函数
- C++将 toString 替换为重载的输出运算符
- 尝试过载输出运算符时出错
- 重载输出运算符给出十六进制数字而不是字符串
- 重载输入/输出运算符,为什么它以这种方式工作而不是以另一种方式工作
- Qt 使用迭代器重载了 qtextstream 输出运算符
- 抽象类和派生类的输出运算符 (<<)
- 重载输出运算符和后置增量运算符时"运算符<<"错误不匹配
- 如何在输出运算符中测试std::showbase或std::noshowbase
- 队列类C++的输出运算符重载
- 变量类型和变量模板的转换和输出运算符
- 重载输出运算符<<以使用 STL 列表迭代器
- C++抽象类的输出运算符
- 重载基类及其派生类(C++)的输出运算符
- 重载输出运算符时出现错误
- 为什么我的输出运算符 <<() 函数定义会导致无法解析的外部符号错误?