自定义类返回只返回整数,不返回字符串。C++

自定义类返回只返回整数,不返回字符串。C++,c++,C++,我正在从一个文件中读取并将该信息存储到一个自定义类列表中,该列表是Node类型的链接列表。但是,当我返回列表时,它只返回int并删除所有字符串和向量 List & importMaster() { fstream file; int i = 0, check = 0; Node students[10]; List master1; char temp[200]; file.open("master.txt", ios::in);

我正在从一个文件中读取并将该信息存储到一个自定义类列表中,该列表是Node类型的链接列表。但是,当我返回列表时,它只返回int并删除所有字符串和向量

List & importMaster()
{
    fstream file;
    int i = 0, check = 0;
    Node students[10];
    List master1;
    char temp[200];
    file.open("master.txt", ios::in);

    while (!file.eof())
    {

        file.getline(temp,50);
        int recordNum = atoi(temp);
        file.getline(temp, 40);
        int ID = atoi(temp);
        file.getline(temp, 40, '"');
        file.getline(temp, 40, '"');
        const string name = temp;
        file.getline(temp, 40);
        file.getline(temp, 40);
        string email = temp;
        file.getline(temp, 40);
        int units = atoi(temp);
        file.getline(temp, 40);
        string program = temp;
        file.getline(temp, 40);
        const string level = temp;
        file.getline(temp, 40);
        int numAbscence = atoi(temp);
        vector <string> absences;

        for (int j = 0; j < numAbscence; j++)
        {
            file.getline(temp, 40);
            absences.push_back(temp);
        }

        //gets extra line between 
        file.getline(temp, 40);

        students[i] = Node(recordNum, ID, name, email, units, program, level, numAbscence, absences);

        if (i > 0)
        {
            students[i].setNextNode(&students[i - 1]);
        }

        master1.setMaster(&students[i]);

        i++;
    }

    return master1;
}

您将返回一个引用列表&to master,它是堆栈上的一个列表-这是不好的,因为一旦返回,master就超出范围,并且master所在的堆栈部分很可能很快将用于另一个局部变量

您可以将其更改为只返回List而不是List&,并希望编译器通过RVO=返回值优化来优化副本。或者,您可以显式执行RVO的基本操作并传入引用,例如:

void importMaster(List& outMaster)
{
    // same as before, just remove the "List master1;" line
    // and replace-all master1 with outMaster
}
然后做:

List masterList;
importMaster(masterList)
然而,即使如此,我怀疑您可能对以下几行有问题:

students[i].setNextNode(&students[i - 1]);
及 硕士1.硕士与学生[i]

在没有看到实现的情况下,很难判断它们是挂在传入的指针上,还是复制了对象-但是如果它们只是挂在指针上,那么一旦学生超出范围,即当您从该函数返回时,它们就会变得无效


你也没有做任何边界检查,所以如果我得到>=10,那么你就要开始在堆栈上跺脚了

条件!file.eof不正确。请发布一个包含所需声明和定义的文档。您肯定需要知道setMaster正在做什么。看起来它可能只是存储一个指向将超出范围的局部变量的指针,但我们不知道