c++中重载<<操作符

来源:互联网 发布:windows 7正常没声音 编辑:程序博客网 时间:2024/04/29 06:06

在类定义中,有时候我们需要直接利用cout来打印出类中的数据,此刻就需要重载<<操作符来实现

假定定义了一个类Time

然后声明了一个类 Time a;

cout<<a<<endl;

这样的语法肯定是会报错的,

此刻就需要重载operator<<

要怎么做呢? 首先,在重载函数中,要访问到类Time中的私有成员的数据,所以我们需要定义这个函数为类Time的友元函数,具体如下

class Time{

friend std::ostream& operator<<(std::ostream & os , const Time & t);

}


std::ostream operaotr<<(std::ostream & os , const Time & t){

os<< t.hours<<"   "<<t.minutes <<endl;

return os;

}


具体使用方法,假定写入到一个文件中

fstream fout;

fout.open(123.txt);

Time t(12 , 40);

fout<<trip<<endl;

fout.close();


以上就实现了将<<重载的内容保存到文件123.txt中了



1 0
原创粉丝点击