gpt4 book ai didi

c++ - 学习 C++ : error: use of deleted function

转载 作者:太空宇宙 更新时间:2023-11-04 15:13:38 28 4
gpt4 key购买 nike

我正在做“像程序员一样思考”一书中的一些练习,到目前为止一切都很好。我开始了类(class)一章,在这里我似乎被卡住了,因为我无法解决编译代码时遇到的错误。

这是代码。这不是我的,我一直在写这本书试图理解它。

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()’

最佳答案

当您定义一个 struct 时,例如:

struct studentNode {
studentRecord studentData;
studentNode *next;
};

它有一个隐式定义的默认构造函数,相当于:

struct studentNode {
studentNode() : studentData(), next() {}
studentRecord studentData;
studentNode *next;
};

这是一个问题,因为 studentRecord 的默认构造函数由于存在用户定义的构造函数而被编译器删除。

您可以将默认构造函数添加到 studentRecord 以解决该问题。

struct studentRecord {
int studentId;
int grade;
string name;
studentRecord() = default;
studentRecord(int a, int b, string c);
};

与其使用带有 = default; 说明符的计算机生成的默认构造函数,不如使用有效数据初始化对象会更好。

struct studentRecord {
int studentId;
int grade;
string name;
studentRecord() : studentRecord(0, 0, "") {} // Delegate to the other constructor.
studentRecord(int a, int b, string c);
};

关于c++ - 学习 C++ : error: use of deleted function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43457382/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com