【发布时间】:2019-11-19 01:57:56
【问题描述】:
我想在 C++ 中创建 Node like Arraylist。当我创建一个方法 get();它说的是错误。不明白什么时候去网上找答案。你能帮我找到这个答案吗?
template<typename T>
struct Node{ //Node
T data;
Node<T> *next;
Node(){
next=NULL;
}
Node(T value){
data=value;
next=NULL;
}
};
template<typename T>
class LinkedList{ //class Node
public:
Node<T> *head;
Node<T> *tail;
void add(T value){ //method create newnode add to tail
Node<T> *newNode=new Node<T>(value);
if (head == NULL){
head=newNode;
tail=newNode;
}
else {
tail->next=newNode;
tail=newNode;
}
}
void PrintAll(string Name){ //method print all node
Node<T> *current;
int i=0;
current=head;
while (current != NULL ){
printf("%s[%d]=%d\n",Name.c_str(),i,current->data);
current=current->next;
i++;
}
}
T get(int index){ //method show node in parameter
Node <T> *current=head;
int count=0;
while (current != NULL){
if ( count == index) return current->next;
current=current->next;
count++;
}
}
};
错误:从 'Node*' 到 'int' 的无效转换 [-fpermissive]| 警告:控制到达非空函数的末尾 [-Wreturn-type]|
【问题讨论】:
-
T get(int index)应该返回一个 T。它没有返回任何东西。 -
在 T get(int index) 函数中,您没有在末尾放置任何 return 语句。它应该返回 T
-
正如@LightYagami 提到的,您在
get函数中有一条不返回的路径。这可能会导致未定义的行为。
标签: c++ list templates exception singly-linked-list