【问题标题】:ifstream-istream and function callifstream-istream 和函数调用
【发布时间】:2017-02-25 12:14:31
【问题描述】:

我是 C++ 新手,在处理流时,我看到了以下代码:

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;

class Results
{
    public:

        string const& operator[](int index) const
        {
            return m_data[index];
        }
        int size() const
        {
            return m_data.size();
        }
        void readnext(istream& str)
        {
            string line;
            getline(str, line);
            cout << "line :" << line <<endl;

            stringstream lineStream(line);
            string cell;

            m_data.clear();
            while(getline(lineStream, cell, ','))
            {
                m_data.push_back(cell);
                cout << cell<<endl;
            }

        }
    private:
        vector<string> m_data;
};



istream& operator>>(istream& str, Results & data)
{

    data.readnext(str);
    return str;
}   



int main()
{
    ifstream file("filename.txt");
    Results r1;
    while(file >> r1)
    {
        cout << "1st element: " << r1[3] << "\n";
    }
}

当调用data.readnext(str) 时: 1)作为参数传递的str 的值是多少?当我打印出来时,我得到 0x7ffd30f01b10 这是一个地址。 2)在函数getline(str, line); 中给出文件第一行的值。我不明白为什么。那不应该是getline(file, line); 我通常不明白这是如何工作的,因此非常感谢任何帮助

【问题讨论】:

标签: c++ ifstream istream


【解决方案1】:
  1. 该值是对实例化的std::ifstream file 对象的std::istream 超类的引用。

  2. 没有。在readnext() 函数的范围内没有可见的file 对象。代码是正确的。 strstd::istream &amp;参数到readnext(),第一个参数的类型匹配到std::getline()

【讨论】:

  • “子对象”可能会更好
  • 所以 str 是对 std::ifstream 文件对象的引用?
  • 如果您看一下str 被声明为什么,作为readnext() 函数的参数,您应该能够回答自己的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-29
  • 2016-12-12
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
相关资源
最近更新 更多