問題的疑難解答詳述如下:爲什麼我得到錯誤說studentList
和indexPtr
未在此範圍內聲明?針對結構數組的指針作用域和構造函數的創建
我寫了一個應該創建一個結構數組並允許用戶在該數組中添加,刪除和打印項目的程序。該程序運行良好,但我無法獲得添加,刪除和打印功能自己正常工作。如果我在主函數中擁有所有的代碼,那麼一切工作都很完美。
現在我試圖重寫我的程序,並通過將所有信息發送到適當的函數來工作,但我不明白從我的主函數來回發送信息的正確方法。
這裏是我的聲明我的頭文件:
#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++;
}
}
我覺得一切都在我的計劃將有一次我工作獲得關於指針和我陣列的初始創建的信息。非常感謝您的幫助!
編輯: 這裏是我的主要功能的一個片段,只是爲了顯示我如何打電話學生構造,並試圖調用函數在學生類:
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);
}
對於我來說,至少你的實際問題還不清楚...... – 2013-02-23 16:32:23
@MatsPetersson我不知道爲什麼我會收到錯誤,指出'studentList'和'indexPtr'沒有在此範圍內聲明。我認爲這是因爲我做錯了我的構造函數,但我不知道。 – manalishi 2013-02-23 16:34:49