【问题标题】:Overloaded function calling function with same name but different parameters重载函数调用同名但参数不同的函数
【发布时间】:2014-01-21 04:35:00
【问题描述】:

我正在创建一个链接列表。我想调用函数

addToTail(head*, data)

从函数

  addToTail(head*){int n = length(head*);  addtoTail(head*, n)}

其中包含一个计算列表长度的函数。

不幸的是,这给了我一个错误

\linkedList.cpp:97:16: error: too few arguments to function 'void addAtTail(node*, int)'

这对我来说似乎很有意义,我做错了什么吗?

这里是代码。任何改进它的 cmets 将不胜感激。

#include<iostream>

using namespace std;

struct node
{
    int data;
    struct node* next;
};

void changeToNull(struct node** head)
{
    *head = NULL;
}

int listLength(struct node* head)
{
    struct node* curr = head;
    int i = 0;
    while(curr!=NULL)
        {
        i++;
        curr = curr->next;
        }
    return i;
}



void addAtTail(struct node* head)
{
    int length = listLength(head);
    addAtTail(head, length);
}

void addAtTail(struct node* head, int n)
{
    struct node* newNode = new node;
    struct node* curr = new node;
    newNode->next = NULL;
    newNode->data = n;
    curr= head;
    while(curr->next!=NULL)
    {
        curr = curr->next;
    }
    curr->next = newNode;
}

int main()
{
    //changeToNull(&head);
    addAtTail(head);
    printList(head);
    return 0;
}

【问题讨论】:

    标签: c++ function linked-list overloading singly-linked-list


    【解决方案1】:
    addToTail(head*){int n = length(head*);  addtoTail(head*, n)}
    

    这里head* 是一个类型名,而不是一个自变量参数。你需要这样做:

    addToTail(node* head){int n = length(head);  addtoTail(head, n)}
    

    笔记: 你没有length(node*) 定义,你定义了:

    listLength(struct node*);
    

    所以你应该使用int n = listLength(head)

    【讨论】:

    • 我不明白为什么它是一个类型名。我以为我的 typename 是“node*”,而“head”是参数。
    • 那么你应该写 (node* head)
    猜你喜欢
    • 1970-01-01
    • 2013-10-06
    • 2015-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-04
    • 1970-01-01
    相关资源
    最近更新 更多