【问题标题】:How to pass a global variable into a function in C++?如何将全局变量传递给 C++ 中的函数?
【发布时间】:2018-09-06 02:59:21
【问题描述】:

我目前正在学习解析一个包含学生成绩数据的文件。

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;
}

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

【问题讨论】:

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


    【解决方案1】:

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

    但是,您可以将句柄传递给fstream,从而允许函数使用调用者的对象而无需复制。 C++ 风格要求引用,C 爱好者可能会使用指针。要使用引用,调用者无需更改,只需修改函数签名即可。

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

    注意不清楚为什么你同时传递fstream 和文件名。如果您传递文件名,该函数可以创建自己的fstream 对象,并且不需要在参数中添加一个。或者,让调用者打开fstream 并传递它;这更灵活,因为调用者还可以在文件中设置读取开始的位置。在这种情况下,函数不需要文件名,因为它使用的是已经打开的流。

    【讨论】:

    • 作为一个以前只用过 Python 和 Java 编程的人,引用和指针对我来说是一个有点新奇的概念。如果我的理解是正确的,通过传入引用,我不是在创建对象的副本,而是创建对对象内存地址的“引用”,而不是对对象本身起作用?如果这是真的,该函数最终如何创建另一个 fstream 对象?
    • @IkechukwuAnude:您在问题中显示的代码没有通过引用。我向您展示了在何处添加一个字符 (&amp;) 以使用参考。还是你最后问的是我的笔记?
    • 是的,我问的是最后的注释。
    • @IkechukwuAnude:您想了解更多关于两条路径中的哪一条?传递(仅)fstream,还是传递(仅)文件名?
    • 通过(仅)fstream。但我也有一个问题:其余代码看起来应该像我描述的那样运行吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 2015-10-15
    • 1970-01-01
    • 2013-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多