首页 > 其他 > 详细

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

时间:2016-07-09 10:25:13      阅读:139      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!