C++重载流插入运算符与流提取运算符

C++重载流插入运算符与流提取运算符

1.1 "<<" 流插入运算符,">>"流提取运算符。
1.2对“<<”和“>>”重载的函数的形式如下:
istream & operator >> (istream &,自定义的类&);
ostream & operator << (ostream &,自定义的类&);
即重载运算符的第一个参数和函数类型必须是istream或者ostream类型的,第二个参数是要操作的类。
这是为了能连续的输入和输出。
1.3只能重载"<<"和">>"作为友元函数或者普通函数,而不能将他们定义为成员函数。(因为<<和>>的左边必须是ostream或者istream而成员函数不可以了)
1.4代码参考
#include <iostream>
 
 
using namespace std;
 
 
class Complex
{
public:
    Complex(){real=0;image=0;}
    Complex(int r,int i):real(r),image(i){}
    Complex operator + (Complex &c);
    Complex(int r){real=r;image=0;}
    friend ostream& operator << (ostream& output,Complex& c);
    friend istream& operator >> (istream& input,Complex& i);
private:
    int image,real;
};
 
 
Complex Complex::operator +(Complex &c)
{
    return Complex(c.real+real,c.image+image);
}
 
 
ostream& operator << (ostream& output,Complex& c)
{
    output << "(" << c.real << "+" << c.image << "i" << ")" << endl;
    return output;
}
 
 
istream& operator >> (istream& input,Complex& i)
{
    cout << "please input real and image" ;
    input >> i.real >> i.image;
    return input;
}
 
 
int main()
{
    Complex c1,c2;
    Complex c3(1);
    cin >> c1 >> c2;
    cout << c1+c2 << endl;
    cout << c3 << endl;
    return 0;
}
 
 
 
 

  • 7
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值