C++的流插入运算符“<<”和流提取运算符“>>”的重载

C++的流插入运算符“<<”和流提取运算符“>>”是C++在类库中提供的,所有C++编译系统都在类库中提供输入流类istream和输出流类ostream。cin和cout分别是istream类和ostream类的对象。在类库提供的头文件中已经对“<<”和“>>”进行了重载,使之作为流插入运算符和流提取运算符,能用来输出和输入C++标准类型的数据。因此,凡是用“cout<<”和“cin>>”对标准类型数据进行输入输出的,都要用#include 把头文件包含到本程序文件中。

用户自己定义的类型的数据,是不能直接用“<<”和“>>”来输出和输入的。如果想用它们输出和输入自己声明的类型的数据,必须对它们重载。

对“<<”和“>>”重载的函数形式如下:
istream & operator >> (istream &, 自定义类 &);
ostream & operator << (ostream &, 自定义类 &);
即重载运算符“>>”的函数的第一个参数和函数的类型都必须是istream&类型,第二个参数是要进行输入操作的类。重载“<<”的函数的第一个参数和函数的类型都必须是ostream&类型,第二个参数是要进行输出操作的类。因此,只能将重载“>>”和“<<”的函数作为友元函数或普通的函数,而不能将它们定义为成员函数;

file:Complex.h

#pragma once
#include <iostream>
using namespace std;
class Complex
{
public:
    Complex(){real = 0; imag = 0;}
    Complex(double r, double i){ real = r; imag = i; }
    friend ostream &operator<<(ostream&, Complex&);
    friend istream &operator>>(istream&, Complex&);
    Complex operator+(Complex&c2);
private:
    double real;
    double imag;
};

fiel:Complex.cpp

#include "stdafx.h"
#include "Complex.h"


ostream& operator<<(ostream&output, Complex&c)
{
    output << "(" << c.real << "+" << c.imag << "i)" << endl;
    return output;
}
istream& operator>>(istream&intput, Complex&c)
{
    cout << "input real part and imaginary part of complex number";
    intput >> c.real >> c.imag;
    return intput;
}
Complex Complex::operator+(Complex& c2)
{
    return Complex(real + c2.real, imag + c2.imag);
}
#include "stdafx.h"
#include "Complex.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
    Complex c1, c2, c3;
    cin >> c1 >> c2;
    c3 = c1 + c2;
    cout << c3;
    system("pause");
    return 0;
}
  • 8
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值