以下に詳述する質問の要点:なぜ私はそれを言っているエラーを受け取りstudentList
、indexPtr
このスコープで宣言されていないのですか?
構造体の配列を作成し、ユーザーがその配列内のアイテムを追加、削除、および印刷できるようにするプログラムを作成しました。プログラムは正常に動作しましたが、追加、削除、および印刷機能を単独で正しく動作させることができませんでした。main関数にすべてのコードが含まれていれば、すべてが完全に機能しました。
現在、プログラムを作り直して、すべての情報を適切な関数に送信することで機能させようとしていますが、メイン関数との間で情報をやり取りする適切な方法がわかりません。
これが私のすべての宣言のヘッダーファイルです:
#include <iostream>
#include <string>
#define MAXSIZE 20;
using namespace std;
class Student
{
private:
struct studentEntry
{
string FIRST;
string LAST;
string ID;
string CLASSIFICATION;
string MAJOR;
};
int index;
public:
void add(string &firstname, string &lastname, string &id, string &classification, string &major);
void remove(string &id);
void print(string &argument);
int commandCompare(string &command);
bool idCheck(string &id);
Student();
};
次に、すべての関数を含むファイルのコードの一部を示します。つまり、学生クラスのコンストラクターである最初のものです。私がやろうとしていたのは、すべての関数で同じ配列を使用できるように、学生構造の配列とインデックスへのポインターを作成することでした。
#include "students.h"
//constructor for Student class to create students array and pointer to index
Student::Student(){
int *indexPtr = &index;
studentEntry *studentList = new student[MAXSIZE];
}
//function to add entry to array of students
void Student::add(string &firstname, string &lastname, string &id, string &classification, string &major)
{
string m_first = firstname;
string m_last = lastname;
string m_id = id;
string m_classification = classification;
string m_major = major;
int error = 0;
//check if id is all digits, print error
if (studentList[indexPtr]->idCheck(id) == false)
{
cout << "Error! ID can only contain digits." << endl;
error = 1;
}
//search match for existing ids
for(int i=0; i<indexPtr; i++)
{
//match found, print error, mark error true
if(id.compare(studentList[i]->student->ID) == 0)
{
cout << "Error! ID already exists." << endl;
error = 1;
}
}
else if(error != 1)
{
studentList[indexPtr]->FIRST = m_first;
studentList[indexPtr]->LAST = m_last;
studentList[indexPtr]->ID = m_id;
studentList[indexPtr]->CLASSIFICATION = m_classification;
studentList[indexPtr]->MAJOR = m_major;
indexPtr = indexPtr++;
}
}
ポインタと配列の最初の作成について少し理解すれば、プログラムのすべてが機能すると思います。助けてくれてありがとう!
編集:これは私のメイン関数のスニペットです。Studentコンストラクターを呼び出し、Studentクラスの関数を呼び出そうとしている方法を示しています。
int main()
{
Student students;
string command;
int quit = 0;
//loop while user command != quit
do
{
cout << "students> ";
cin >> command;
//if user command = add
if(students.commandCompare(command) == 1)
{
string first, last, id, classification, major;
cin >> first >> last >> id >> classification >> major;
students.add(first, last, id, classification, major);
}