自定义类返回只返回我的int而不是我的字符串。 C ++

时间:2016-07-14 04:23:59

标签: c++

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

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

1 个答案:

答案 0 :(得分:0)

你正在将一个引用(List&amp;)返回到master(这是一个堆栈上的List) - 这很糟糕,因为master一返回就会超出范围,并且master可能存在的堆栈部分很可能很快就会被用于另一个局部变量。

您可以将其更改为仅返回List而不是List&amp;,并希望编译器优化副本(通过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]);

和     master1.setMaster(安培;学生[I]);

如果没有看到实现(它们挂在传入的指针上,还是复制对象)是不可能的 - 但是如果它们只是挂在指针上,那么一旦学生超出范围它们就会变得无效(即当你从那个函数返回时)。

你也没有做任何边界检查,所以如果我得到&gt; = 10那么你就会开始在堆栈上踩其他东西