流插入运算符和流提取运算符的重载

#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

class Complex {
public:
    double real, imag;
public:
    Complex(double r = 0, double i = 0): real(r), imag(i){};
    friend ostream& operator<<(ostream& os, const Complex& c);
    friend istream& operator>>(istream& is, const Complex& c);
};

ostream& operator<<(ostream& os, const Complex& c) {
    os << c.real << "+" << c.imag << "i";
    return os;
}

istream& operator>>(istream& is, Complex& c) {
    string s;
    is >> s;
    int pos = s.find("+", 0);
    string sTmp = s.substr(0, pos);
    c.real = atof(sTmp.c_str());
    sTmp = s.substr(pos+1, s.length()-pos-2);
    c.imag = atof(sTmp.c_str());
    return is;
}

int main()
{
    Complex c;
    int n;
    cin >> c >> n;
    cout << c << "," << n;
    return 0;
}

  

 

posted @ 2018-12-23 21:40  Veritas_des_Liberty  阅读(682)  评论(0编辑  收藏  举报