重载istream运算符>> c ++ [英] Overloading istream operator>> c++

查看:152
本文介绍了重载istream运算符>> c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个chars的向量,我把它作为一个字符串,而不是一个字符串的向量推送到流,我将如何使用操作符>>?

Say I have a vector of chars and I pushed it into a stream as a string, rather than a vector of chars, how would i get back the vector of chars using operator>>?

class C{
    private:
        vector<char> c;

    public:
        C(string str){
          for(int x = 0; x < str.size(); x++)
              c.push_back(str[x]);
        }

        vector<char> data(){
           return c;
        }       
};

ostream operator<<(ostream & stream, C & in){
   for(int x = 0; x < in.data().size(); x++)
      stream << in.data()[x];
   return stream;
}

istream operator>>(istream & stream, C & in){
    // ???
    // what kind of loop?
}


推荐答案

像这样....

#include <algorithm>
#include <iterator>
#include <vector>
#include <iostream>
#include <sstream>

class C
{
    std::vector<char> mData;

  public:
    // Constructor, note im using the iterator range 
    // vector constructor.
    C(const std::string& str)
    : mData(str.begin(), str.end())
    {
    }

    // Returning data by const reference to avoid 
    // copying a potentially large object.
    const std::vector<char>& data() const
    {
        return mData;
    }

    // declared the input operator as a friend as I need it to
    // access mData - alternatively you could write a "loadFromStream"
    // type function that does the same, declare this as non-friend, and call that.
    friend std::istream& operator>>(std::istream& is, C& c);
};

std::ostream& operator<<(std::ostream& os, const C& c)
{
    // Use an ostream_iterator to handle output of the vector
    // using iterators.
    std::copy(c.data().begin(), 
              c.data().end(), 
              std::ostream_iterator<char>(os, ""));

    return os;
}

std::istream& operator>>(std::istream& is, C& c)
{
    // load the data using the assign function, which
    // clears any data already in the vector, and copies 
    // in the data from the specified iterator range.
    // Here I use istream_iterators, which will read to the end
    // of the stream.  If you dont want to do this, then you could 
    // read what you want into a std::string first and assign that.
    c.mData.assign(std::istream_iterator<char>(is),
                   std::istream_iterator<char>());

    return is;
}

int main()
{
    C c("Hello");

    std::stringstream ss;
    ss << c;

    std::cout << ss.str() << std::endl;

    C d("");
    ss >> d;

    std::cout << d.data().size() << std::endl;

    return 0;
}

这篇关于重载istream运算符&gt;&gt; c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆