重载_流运算符和函数运算符()

重载流运算符来输入输出用户自己定义的类。
流运算符函数是全局函数,不能作为类的成员来定义。
声明:

// 其中参数为流对象的引用,目标对象的引用。对于输出流,目标对象还要是常量。
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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值