c++ - 链接列表(从 'Node<int>*' 到 'int' [-fpermissive]| 的无效转换)

标签 c++ list templates exception singly-linked-list

我想在 C++ 中创建类似于 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() 中,您返回的是 Node* 而不是 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++;
        }
    }

你还应该处理索引无效的情况,在这些情况下抛出异常是可以的。

关于c++ - 链接列表(从 'Node<int>*' 到 'int' [-fpermissive]| 的无效转换),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56953778/

相关文章:

python - 如何在 Python 中选择嵌套列表中的列表项

c++ - 类模板,无效的空指针(字符串)

c++ - 如何减少大型模板的编译时内存占用?

java - 在 JNI 中将 JString 转换为 String 时的 UTF 8 特殊字符

c# - 如何创建仅允许访问 C++ 中特定用户帐户的手动重置事件?

c++ - 是否有可以解析 C++ 的优秀 Python 库?

java - 使用 ArrayList 访问特定对象 Java

java - 删除单链表中的重复项保留顺序

c++ - 使用模板元编程 [C++11] 对整数列表进行操作

java - 配置速度以使用 toString 以外的东西渲染对象?