首页 > 解决方案 > 链表(来自 '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]|

标签: c++listtemplatesexceptionsingly-linked-list

解决方案


在里面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++;
        }
    }

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


推荐阅读