超载函数调用功能具有相同名称,但参数不同

Overloaded function calling function with same name but different parameters

本文关键字:参数 超载 功能 函数调用      更新时间:2023-10-16

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

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)'

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

这是代码。任何以改进它的评论将不胜感激。

#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;
}
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)