我正在做一些練習,從書中「像程序員一樣思考」,到目前爲止一切都很棒。 我開始了課程章節,在這裏我似乎被卡住了,因爲我無法將我的頭圍繞編譯代碼的錯誤。學習C++:錯誤:使用已刪除的函數
這是代碼。這不是我的,我一直在寫這本書,試圖理解它。
struct studentRecord {
int studentId;
int grade;
string name;
studentRecord(int a, int b, string c);
};
class studentCollection {
private:
struct studentNode {
studentRecord studentData;
studentNode *next;
};
public:
studentCollection();
void addRecord(studentRecord newStudent);
studentRecord recordWithNumber(int idNum);
void removeRecord(int idNum);
private:
//typedef studentNode *studentList;
studentNode *_listHead;
};
studentRecord::studentRecord(int a, int b, string c) {
studentId = a;
grade = b;
name = c;
}
studentCollection::studentCollection() {
_listHead = NULL;
}
void studentCollection::addRecord(studentRecord newStudent) {
studentNode *newNode = new studentNode;
newNode->studentData = newStudent;
newNode->next = _listHead;
_listHead = newNode;
}
studentRecord studentCollection::recordWithNumber(int idNum) {
studentNode *loopPtr = _listHead;
while (loopPtr != NULL && loopPtr->studentData.studentId != idNum) {
loopPtr = loopPtr->next;
}
if (loopPtr == NULL) {
studentRecord dummyRecord(-1, -1, "");
return dummyRecord;
} else {
return loopPtr->studentData;
}
}
int main() {
studentCollection s;
studentRecord stu3(84, 1152, "Sue");
studentRecord stu2(75, 4875, "Ed");
studentRecord stu1(98, 2938, "Todd");
s.addRecord(stu3);
s.addRecord(stu2);
s.addRecord(stu1);
}
我得到的錯誤是:
studentclass1.cpp: In member function ‘void studentCollection::addRecord(studentRecord)’:
studentclass1.cpp:45:32: error: use of deleted function ‘studentCollection::studentNode::studentNode()’
studentNode *newNode = new studentNode;
^~~~~~~~~~~
studentclass1.cpp:17:12: note: ‘studentCollection::studentNode::studentNode()’ is implicitly deleted because the default definition would be ill-formed:
struct studentNode {
^~~~~~~~~~~
studentclass1.cpp:17:12: error: no matching function for call to ‘studentRecord::studentRecord()’
如果這本書是真正教你避免錯誤使用原始的擁有指針和內存泄漏,你應該把它扔掉,[得到一本更好的書](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)。 – nwp
爲什麼你和其他許多人在這裏發帖,發現發佈實際代碼非常困難,並且完成了預處理器指令? –
使用'nullptr'而不是'NULL' –