我试图定义一个自定义模板容器,然后向其中添加自定义类对象(学生)。这是我的代码:
class Student{
public:
string subject;
Student(string _subject){
subject = _subject;
}
};
这是我的LinkedList模板代码
template <class T>
class LinkedList{
private:
struct Node{
Node *next;
T value;
};
Node *root;
Node *curr;
int count;
public:
LinkedList() : count(0), root(NULL){}
void add(T val){
if (root == NULL){
root = new Node;
root->value = val;
root->next = NULL;
curr = root;
}
else{
curr->next = new Node;
curr = curr->next;
curr->value = val;
curr->next = NULL;
}
count++;
}
void print(){
for (Node *itr=root; itr != NULL; itr = itr->next){
cout << itr->value << endl;
}
}
};
int main(){
LinkedList<Student> a;
Student sam("Math");
a.add(sam)
}
当我运行它时,我得到
linkedlist.cpp:在构造函数'LinkedList :: Node :: Node()'中:linkedlist.cpp:27:从'void LinkedList :: add(T)[with T = Student]实例化
linkedlist.cpp:133:从此处实例化
linkedlist.cpp:27:错误:没有匹配函数可以调用'Student :: Student()'linkedlist.cpp:18:注意:候选人是:Student :: Student(std :: string)
linkedlist.cpp:15:注意:Student :: Student(const Student&)linkedlist.cpp:在成员函数'void LinkedList :: add(T)[with T = Student]'中:
linkedlist.cpp:40:注意:此处首先需要综合方法'LinkedList :: Node :: Node()'
我不知道该错误真正意味着什么,以及它在要求我做什么。如果我改为这样做:
int main(){
LinkedList<Student*> a;
Student sam("Math");
a.add(&sam);
}
它工作正常。
但是存储对象的引用不是我想要的。如何获得我的LinkedList来复制我想添加到该对象的对象?
提前致谢!
首先...
#include <utility>
现在,改变这个...
struct Node {
Node* next;
T value;
};
为了...
struct Node {
Node* next;
T value;
inline Node(const T &value) : value(value), next(nullptr) {}
inline Node(T &&value) : value(std::move(value)), next(nullptr) {}
};
和这个...
void add(T val) {
if(this->root == nullptr) {
this->root = new Node;
this->root->value = val;
root->next = NULL;
curr = root;
} else {
curr->next = new Node;
curr = curr->next;
curr->value = val;
curr->next = NULL;
}
count++;
}
为了这...
void add(const T &val){
if(this->root == nullptr) {
this->root = new Node(val);
this->curr = root;
} else {
this->curr->next = new Node(val);
this->curr = this->curr->next;
}
this->count++;
}
void add(T &&val){
if(this->root == nullptr) {
this->root = new Node(std::move(val));
this->curr = root;
} else {
this->curr->next = new Node(std::move(val));
this->curr = this->curr->next;
}
this->count++;
}
发生的情况是您正在使用隐式默认构造函数创建Node
对象new Node
。这意味着将Node::value
调用for的默认构造函数。那你能告诉我是否有吗?否。Student
没有默认的构造函数,因此它将无法正常工作。
顺便说一句,我对您的代码做了一些小的重新设计,以避免出现一些问题。另外,您现在可以使用move语义(try list.add(Student("Joe"))
)!
此外,请记住初始化curr
到nullptr
在构造函数初始化列表!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句