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

cout是在iostream中定义的,是ostream类的对象。cin是istream类的对象。测试代码如下:

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

using namespace std;

class Complex
{
private :
    int real, img;
public:
    friend ostream & operator <<(ostream & o, const Complex &c);
    friend istream & operator >> (istream & is,Complex &c);
};

ostream &operator <<(ostream &o, const Complex &c)
{
    o << c.real << '+' << c.img << 'i';
    return (o);
}
istream &operator >> (istream & is, Complex &c)
{
    string s;
    is >> s;
    int p = s.find('+', 0);
    string sTmp = s.substr(0, p);
    c.real = atof(sTmp.c_str());
    sTmp = s.substr(p + 1, s.length() - p - 2);
    c.img = atof(sTmp.c_str());
    return is;
}
int main()
{
    Complex c;
    int n = 0;
    cin >> c >> n;
    cout << c <<","<< n;
    return 0;
}

 参考链接:

https://www.coursera.org/learn/cpp-chengxu-sheji

原文地址:https://www.cnblogs.com/helloforworld/p/5655250.html