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

来源:互联网 发布:sql join on的用法 编辑:程序博客网 时间:2024/06/05 00:21

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;
}


1 0
原创粉丝点击