错误“未在此范围内声明的标识符” - C ++

时间:2016-02-11 19:25:24

标签: c++ pointers reference

C ++初学者。所以我有几个函数,我试图传递一个指针数组元素(包含结构(记录))。我在做这件事时遇到了麻烦,而且我非常困难和沮丧。我对指针和记忆都很陌生,所以对我来说很容易。当我尝试将特定结构元素传递给函数时,我不断收到错误。 (顺便说一句:函数在头文件中声明)

我该怎么做才能修复/更改它并让它工作?感谢您的帮助,非常感谢。

我得到的错误:

'changeAssignmentGradeForStudent' was not declared in this scope

代码:

结构学生:

typedef struct
{
   char  firstName[50];
   char  lastName[50];
   char  studentNumber[10];
   char  NSID[10];
   float assignments[10];
   float midterm;
   float final;
} Student;


void useFunctions(int recordNum)
{
   // array of 10 student references
   Student *students[recordNum];

   // values received from the user
   for (int i = 0; i < recordNum; i++)
   {
      cout << "Student " << i + 1 << ": " << endl;
      students[i] = readStudentRecordFromConsole();
   }

   cout << "Would you like to make any changes to any student records? (N or Y)" << endl;

   cin >> answer;

   if (answer == 'N')
   {
      return;
   }
   else
   {
      cout << "Which student?" << endl;
      cin >> student;
      students[student - 1] = gradeChanges(*students[student - 1], recordNum, student);
   }
}


Student *gradeChanges(Student *s, int recordNum, int student)
{
   Student *changedStudent = s;
   int     gradeChange, aNum;

   cout << "assignment number to change?" << endl;
   cin >> aNum;
   cout << "assignment to change?" << endl;
   cin >> gradeChange;

   changeAssignmentGradeForStudent(changedStudent, aNum, gradeChange); //  where the errors are
   return changedStudent;
}

void changeAssignmentGradeForStudent(Student *s, int a, int g)
{
   if (s != NULL)
   {
      s->assignments[a] += g;
   }
}

PS:很抱歉,如果我的代码格式不正确。如果不是,请随时编辑,谢谢。

2 个答案:

答案 0 :(得分:0)

函数changeAssignmentGradeForStudent在使用之前未声明或定义,因此编译器尚未了解它。您可以在useFunctions()之前移动函数定义,也可以在文件顶部声明它,如下所示:

void changeAssignmentGradeForStudent(Student*, int, int);

答案 1 :(得分:0)

在引用这些函数之前,编译器需要查看函数的声明。在调用这样的函数之前,你必须放置该声明:

// This is the (forward) declaration:
void changeAssignmentGradeForStudent(Student* s, int a, int g); 

Student * gradeChanges(Student* s, int recordNum, int student) {

    Student *changedStudent = s;
    int gradeChange, aNum;

       cout << "assignment number to change?" << endl;
       cin >> aNum;
       cout << "assignment to change?" << endl;
       cin >> gradeChange;

   changeAssignmentGradeForStudent(changedStudent, aNum, gradeChange); //  where the errors are


   return changedStudent;
}

// This is the definition:
void changeAssignmentGradeForStudent(Student* s, int a, int g)  {

    if (s != NULL) {

        s->assignments[a] += g;

    }

}