如何在C ++中将全局变量传递给函数?

时间:2018-09-06 02:59:22

标签: c++ file oop c++11 visual-c++

我目前正在学习解析一个文件,其中包含有关该学生成绩的一些数据。

std::ifstream f;

int main()
{
    //std::ifstream f;
    parse_store(f, "student_grades.txt"); //this line is throwing the error

    //keep the window from shutting down
    system("pause");

    return 0;
}

parse_store函数解析txt文件,分割每行数据,然后将tokenized向量(看起来像[[Hello],“ World”])发送到要存储的类中在类对象的数组中。

针对上下文:

//parses the file returning a vector of student objects 
std::vector<Student> parse_store(std::ifstream file, std::string file_name) {

    //array of objects
    std::vector<Student> student_info;

    //create string to store the raw lines
    std::string line;

    // the delimiter
    std::string delimiter = " ";

    //open te file
    file.open(file_name);

    //create vector to hold the tokenized list
    std::vector<std::string> tokenized;

    //index
    int index = 0;
    while (file) { 

        //keep track of the index
        index++;

        //create a vector to hold each student's grades (will hold the objects)
        std::vector<std::vector<std::string>> grades = {};

        //read a line from file
        std::getline(file, line);

        //delimit the line and send it to the constructor
        tokenized = delimitMain(line, delimiter);
        student_info.push_back(Student(tokenized, index));
    }

    file.close();

    return student_info;
}

为什么上面的行抛出错误?我将文件对象放入向量然后返回它的方式是否存在问题?

1 个答案:

答案 0 :(得分:4)

您不能通过值传递fstream实例,因为这需要进行复制,并且无法复制iostream对象。

但是,您可以将句柄传递给fstream,从而使函数无需复制即可使用调用者的对象。 C ++样式需要引用,C爱好者可以使用指针。要使用引用,调用者无需进行任何更改,只需修改函数签名即可。

std::vector<Student> parse_store(std::ifstream& file, std::string file_name)
                              // insert this ^^^

目前尚不清楚为什么同时传递fstream和文件名。如果传递文件名,则该函数可以创建自己的fstream对象,并且不需要在参数中添加任何对象。或者,让呼叫者打开fstream并将其传递;这更加灵活,因为调用方还可以在文件中开始读取的位置进行设置。在那种情况下,该函数不需要文件名,因为它使用的是已经打开的流。

相关问题