通过引用和const函数传递

时间:2013-12-01 03:52:21

标签: c++ pointers const

基本上我需要将两个StudentType *函数更改为const但是我知道它不会让我因为ReadStudentData函数上的& ampersand符号而存在这个问题吗?

我不是要求某人做我的命令,只是指出我正确的方向

当我尝试在其中抛出const时会出现一大堆错误

这就是我想要的:

StudentType * SortStudentByName(const StudentType* student, int size);

void ReadStudentData(ifstream& infile, StudentType*& student,
                     int& numOfStudents)
{
    string firstName, lastName;
    int testScore;
    int count = 0;

    infile >> numOfStudents;

    try {
        student = new StudentType[numOfStudents];
        while (infile >> firstName >> lastName >> testScore) {
            if (testScore >= 0 && testScore <=100) {
                student[count].studentName = lastName + ", " + firstName;
                student[count].testScore = testScore;
                count++;
            }
        }
        numOfStudents = count;
    } catch (bad_alloc) {
        cout << "Failed to allocate memory" << endl;
        numOfStudents = 0;
        student = NULL;
    }
}


StudentType* SortStudentsByName(StudentType* student, int numStudents) {
    int startScan, minIndex;

    for (startScan = 0; startScan < (numStudents-1); startScan++) {
        minIndex = startScan;
        for (int index = startScan; index < numStudents; index++) {
            if (student[index].studentName < student[minIndex].studentName)
                minIndex = index;
        }
        StudentType temp = student[minIndex];
        student[minIndex] = student[startScan];
        student[startScan] = temp;    
    }
    cout << endl;
    cout << "List of Students sorted Alphabetically "<< endl;
    DisplayAllStudents(student, numStudents);

    return student;
}

StudentType* SortStudentsByScore(StudentType* student, int numStudents) {
    int startScan, minIndex;
    for (startScan = 0; startScan < (numStudents-1); startScan++) {
        minIndex = startScan;
        for ( int index = startScan; index < numStudents; index++) {
            if( student[index].testScore>student[minIndex].testScore)
                minIndex = index;
        }
        StudentType temp = student[minIndex];
        student[minIndex] = student[startScan];    
        student[startScan] = temp;
    }
    cout <<"List of Students sorted by Score from Highest to Lowest" << endl;
    DisplayAllStudents(student, numStudents);
    return student;
}

0 个答案:

没有答案