代码之家  ›  专栏  ›  技术社区  ›  callisto

需要初学者帮助C++语法

  •  1
  • callisto  · 技术社区  · 16 年前

    我正忙于一项作业,我正从编译器中得到一个错误。我在C++中有4年的C经验。

    我在第行收到错误“从nodeType的无效转换,正在初始化void LinkedListType::DeleteNode(const type&)[with type=int]” deleteNode(current->link); 此功能的:

    template<class Type>
    void linkedListType<Type>::deleteNodePosition(int position)
    {
        nodeType<Type> *current; //pointer to traverse the list
        nodeType<Type> *trailCurrent; //pointer just before current
    
        if(first == NULL)    //Case 1; list is empty. 
            cerr<<"Can not delete from an empty list.\n";
        else
        {
            current = first;
            int counter = 0;
    
            while(current != NULL && counter <= position)
                {               
                    trailCurrent = current;
                    current = current->link;
                    counter++;
                } // end while
            deleteNode(current->link);
        }
    

    DeleteNode定义为:

    template<class Type>
    void linkedListType<Type>::deleteNode(const Type& deleteItem)
    {
        .....
    

    节点类型定义为:

    struct nodeType
    {
        Type info;
        nodeType<Type> *link;
    };
    

    我称之为冒犯性功能:

    linkedListType<int> llist;
    llist.insertFirst(99);
    llist.insertLast(94);
    llist.deleteNodePosition(2);
    

    请帮忙?

    4 回复  |  直到 16 年前
        1
  •  4
  •   Tyler McHenry    16 年前

    问题很简单。这是:

    current->link
    

    定义为具有类型

    nodeType<Type>*
    

    但你要传递给的函数

    void linkedListType<Type>::deleteNode(const Type& deleteItem)
    

    接受类型为的参数

    const Type&
    

    自从 nodeType<Type>* 和…完全不一样 const Type& ,该函数不能接受该参数。

    如果看不到代码的其余部分,很难推断出您要做什么,但我认为基于它的名称, deleteNode 函数应该接受一个节点(即 节点类型<类型>。* )而不是节点所包含的一段数据。

        2
  •  1
  •   naivnomore    16 年前

    您的DeleteNode方法应具有以下签名:

    template<class Type>
    void linkedListType<Type>::deleteNode(const nodeType<Type>& deleteItem)
    

    另外,while循环也有问题。当前值可能为空,在这种情况下调用DeleteNode将是灾难性的。

        3
  •  0
  •   Paul Nathan    16 年前

    DeleteNode采用常量类型&。您正在传递一个nodeType*。

        4
  •  0
  •   Peter Milley    16 年前

    current->link 属于类型 nodeType<Type> * 但是 deleteNode 应为类型的参数 Type & .

    给定名称(即,您正在删除 结点 )我想签名 删除程序 需要改变。