#include<iostream>
using namespace std;
class Time
{
private:
int hours;
int min;
friend void operator<<(Time t,ostream &co);
public:
Time()
{
hours = 0;
min = 0;
}
Time(int x, int y)
{
hours = x;
min = y;
}
};
void operator<<(Time t, ostream &co )//这里ostream 为什么只能使用引用?把&去掉就错了?
{
co << t.hours << ' ' << t.min;
}
int main()
{
Time f1(43, 54);
f1 << cout;
}

操作符重载 ostream为什么只能是引用 自己写的 Time类的对对象就没问题
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
1条回答 默认 最新
- Master Cui 2021-01-11 21:10关注
因为不能对IO对象进行拷贝和赋值,无法用一个IO对象初始化另一个IO对象或给另一个对象赋值
如果是按照非引用方式传参,那么就对IO对象进行拷贝和赋值,违反了上述规则
具体示例见我的博客https://blog.csdn.net/Master_Cui/article/details/107309990
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 1无用