重载<<运算符std :: ostream [英] Overloading << operator for std::ostream
问题描述
ostream& operator<<<(ostream& osObject,const storageRentals& rentals)
{
osObject< rental.summaryReport();
return osObject;
}
summaryReport()
是一个void函数,它给我一个错误:
无操作符<匹配这些操作数
但错误不存在,如果我更改 summaryReport
函数到一个 int
,但我的问题是,你必须返回一个值,它是在屏幕上打印出来。
void storageRentals :: summaryReport()const
{
for(int count = 0; count< 8; count ++)
cout<< 单位:< count + 1< < stoUnits [count]< endl;
}
有任何方法来重载 cout< ; c>你应该定义
summartReport code>以
ostream&
作为参数,如下所示:
std :: ostream& storageRentals :: summaryReport(std :: ostream& out)const
{
//使用out而不是cout
for(int count = 0; count< 8; count ++)
out<< 单位:< count + 1< < stoUnits [count]< endl;
return out; // return so that op<<可以只是一条线!
}
然后调用:
ostream& operator<<<(ostream& osObject,const storageRentals& rentals)
{
return rentals.summaryReport(osObject); //只有一行!
}
顺便说一句,它不是调用overloading cout。您应该说, std :: ostream
重载运算符<<
/ p>
ostream& operator <<(ostream& osObject, const storageRentals& rentals)
{
osObject << rentals.summaryReport();
return osObject;
}
summaryReport()
is a void function, and it is giving me an error:
no operator "<<" matches these operands
but the error is not there if I change the summaryReport
function to an int
, but the problem I have with that is you have to return a value, and it is printing it out on the screen.
void storageRentals::summaryReport() const
{
for (int count = 0; count < 8; count++)
cout << "Unit: " << count + 1 << " " << stoUnits[count] << endl;
}
Is there any way to overload cout <<
with a void function?
You should define summartReport
taking ostream&
as parameter, as shown here:
std::ostream& storageRentals::summaryReport(std::ostream & out) const
{
//use out instead of cout
for (int count = 0; count < 8; count++)
out << "Unit: " << count + 1 << " " << stoUnits[count] << endl;
return out; //return so that op<< can be just one line!
}
then call it as:
ostream& operator <<(ostream& osObject, const storageRentals& rentals)
{
return rentals.summaryReport(osObject); //just one line!
}
By the way, it is not called "overloading cout". You should say, "overloading operator<<
for std::ostream
.
这篇关于重载<<运算符std :: ostream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!