ifstream istream和函数调用

ifstream-istream and function call

本文关键字:函数调用 istream ifstream      更新时间:2023-10-16

我是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( 在函数CCD_ 3中,将文件的第一行的值赋予行。我不明白为什么。那不应该是getline(file, line);吗我通常不理解这是如何工作的,因此任何帮助都将不胜感激

  1. 该值是对实例化的std::ifstream file对象的std::istream超类的引用。

  2. 没有。在readnext()函数的作用域中没有可见的file对象。代码正确。strreadnext()std::istream &参数,并且将第一个参数的类型与std::getline()匹配。