c++ - 链表(来自 'Node 的无效转换*' 到 'int' [-fpermissive]|)
问题描述
我想在 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]|
解决方案
在里面get()
,你正在返回 aNode*
而不是,确切地说是T
在里面。if
你可能应该这样做:
T get(int index){ //method show node in parameter
Node <T> *current=head;
int count=0;
while (current != NULL){
if ( count == index) return current->data;
current=current->next;
count++;
}
}
您还应该处理索引无效的情况,在这些情况下抛出异常是可以的。
推荐阅读
- mongodb - 如何加密/解密 MongoDB
- angular - 我该怎么做才能使折线图中的线条使用 d3 减少锯齿状
- python - 彼此相交的堆叠条形图
- typescript - 区分联合和重新定义属性类型
- python - 如何在 SQL 中插入元组列表
- r - 来自 r 包 googleVis 的 gvisMotionChart() 在浏览器中生成空白图?
- python - 如何从 Python 脚本调用 Bash 脚本函数
- ios - Swift - UserDefaults 设置未保存在框架内
- python - 是否有用于绘制尖峰图的 Python 包
- android - 为什么改造响应内部的价值与外部的价值不同?