C++中重载输入输出运算符时为何需传递time类的引用?
为什么重载>>和<<运算符时需要传递time类的引用?
先搞懂值传递和引用传递的核心区别
- 值传递:函数参数是原对象的副本,函数里对参数的所有操作都只影响这个副本,和原对象无关,函数结束后副本直接销毁。
- 引用传递:函数参数是原对象的别名,操作参数就是直接操作原对象本身,修改会直接作用在原对象上。
针对你的operator>>(输入运算符)
这个运算符的核心目的是把用户输入的时间数据写入到你定义的time对象里。如果用值传递(比如void operator>>(istream &in, time t)):
你在函数里给t.hh、t.mm、t.ss赋值,本质上是给原对象的副本赋值。函数执行完,副本被销毁,main里的t1、t2根本没接收到输入的数据——如果类成员没初始化,输出的就是垃圾值;就算像你代码里那样给成员设了默认值hh=0,mm=0,ss=0,输出的也只是默认值,不是用户输入的内容。
换成引用传递time &t后,函数里的t就是main里原对象的别名,输入的数据直接写入原对象,后续输出自然能拿到正确的结果。
针对你的operator<<(输出运算符)
虽然输出只是读取对象数据,值传递也能拿到正确内容,但用引用(最好是const time &t)有两个关键好处:
- 避免不必要的拷贝:值传递会创建对象副本,浪费内存和CPU资源,尤其是当类的成员很多、体积很大时,开销会很明显。
- 保证只读语义:加
const修饰后,编译器会阻止函数里意外修改对象的操作,符合输出操作“只读取不修改”的逻辑。你的代码里现在没加const,建议改成friend void operator<<(ostream &out, const time &t);,同时函数定义也对应修改,这样更规范。
额外说下你的operator==
这里用值传递是可以的,因为只是比较两个对象的内容,不需要修改原对象。但同样推荐改成const time &t1, const time &t2,避免拷贝,提升效率,同时明确函数不会修改输入对象。
你的源代码:
#include <iostream> using namespace std; class time{ int hh=0,mm=0,ss=0; public: friend void operator>>(istream &in,time &t); friend void operator<<(ostream &out,time &t); friend void operator==(time,time); }; void operator>>(istream &in,time &t){ cout<<"enter hours:";in>>t.hh;cout<<endl; cout<<"enter minutes:";in>>t.mm;cout<<endl; cout<<"enter seconds:";in>>t.ss;cout<<endl; } void operator<<(ostream &out,time &t){ out<<"hours :"<<t.hh;out<<endl; out<<"minutes :"<<t.mm;out<<endl; out<<"seconds :"<<t.ss;out<<endl; } void operator==(time t1,time t2){ if (t1.hh == t2.hh && t1.mm == t2.mm && t1.ss == t2.ss) { cout<<"same time"; } else cout<<"different time"; } int main(){ time t1,t2; cin>>t1; cout<<t1; cin>>t2; cout<<t2; t1 == t2; return 0; }
内容的提问来源于stack exchange,提问作者Amul Pandey
相关产品推荐
相关产品推荐

