aaaaaa
//实现<<重载 在类内的output是因为重载的不能直接获取private内容
void currency::output(ostream& out)const {//把货币值插入流out
long theAmount = amount;
if (theAmount < 0) {
out << '-';
theAmount = -theAmount;
}
long dollars = theAmount / 100;
out << '$' << dollars << '.';
int cents = theAmount - dollars * 100;
if (cents < 10)
out << '0';
out << cents;
}
ostream& operator<<(ostream& out, const currency& x)
{
x.output(out);
return out;
}
//法二
//在类内设为友元函数
//类外情况
ostream& operator<<(ostream& out, const currency& x)
{
long theAmount = amount;
if (theAmount < 0) {
out << '-';
theAmount = -theAmount;
}
long dollars = theAmount / 100;
out << '$' << dollars << '.';
int cents = theAmount - dollars * 100;
if (cents < 10)
out << '0';
out << cents;
return out;
}
本文探讨了在C++中实现货币类的输出重载方法,通过两种方式:一是将重载放置于类内部,二是将其设为友元函数在类外实现,解决了私有成员访问的问题。

被折叠的 条评论
为什么被折叠?



