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

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

posted @ 2016-07-09 09:53  helloforworld  阅读(507)  评论(0编辑  收藏  举报