码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-07-09 10:28:01      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

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

 

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

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!