重载流运算符来输入输出用户自己定义的类。
流运算符函数是全局函数,不能作为类的成员来定义。
声明:
// 其中参数为流对象的引用,目标对象的引用。对于输出流,目标对象还要是常量。
istream& operator>> (istream& in,Test & t1);
ostream& operator<< (ostream& out,const Test & t2);
// 使用时可以使用友元函数,来给予输入输出流重载函数读取对象的私有数据的权利。
例子
#ifndef test_h
#define test_h
#include<iostream>
using namespace std;
class Line{
private:
int a;
public:
Line(){}
Line(int x) {a=x;};
friend istream& operator>>(istream & in ,Line& sca);
friend ostream& operator<<(ostream & out,const Line& pri);
};
#endif /* test_h */
#include<iostream>
#include "test.h"
using namespace std;
istream& operator>>(istream& in,Line& sca){
in>>sca.a;
return in;
}
ostream& operator<<(ostream& out,const Line& pri){
out<<pri.a;
return out;
}
int main()
{
Line L(1);
cout<<L<<endl;
cin>>L;
cout<<L<<endl;
return 0;
}
*****************************
重载函数运算符()
实例1: 函数对象,看上去和函数差不多
#include<iostream>
using namespace std;
class Test{
public:
int operator() (int a,int b)
{
return a+b;
}
};
int main()
{
Test sum;
int ans=sum(1,2);
cout<<ans<<endl;
return 0;
}
实例2:比较大小
using namespace std;
class Test{
private:
int t;
public:
Test(int x) :t(x){};
bool operator() (int);
};
bool Test::operator() (int v){
return (v>t);
}
int main()
{
Test test(2);
int a[5]={4,0,1,5,3};
for(int i=0;i<5;i++){
if(test(a[i]))
cout<<a[i]<<endl;
}
return 0;
}