繁体   English   中英

C ++-没有匹配的函数可调用

[英]C++ - No matching function to call to

我正在制作一个单链表:

#include <conio.h>
#include <iostream>
#include <stdlib.h>

using namespace std;

struct node
{
    int a;
    struct node *ptr;
};

node::node(int p) : {}

struct node *head;

void create(int d)
{
    if(head==NULL)
    {
        head->a=d;
        head->ptr=NULL;
    }
    else
    {
        struct node* temp =(struct node*) malloc(sizeof(struct node));
        temp=head;
        while(temp==NULL)
            temp=temp->ptr;
        temp->a=d;
        temp->ptr=NULL;
    }

}

void display()
{
    struct node* temp =(struct node) malloc(sizeof(struct node));
    temp=head;
    while(temp==NULL)
    {
        cout<<temp->a<<" --> ";
        temp=temp->ptr;
    }
    cout<<endl;
}

int main()
{
    head=NULL;
    create(5);
    create(6);
    create(8);
    display();
    return 0;
}

尝试编译时出现此错误:

..\linkedlist.cpp: In function 'void display()':
..\CPP\linkedlist.cpp:36:61: error: no matching function for call to 'node::node(void*)'
..\CPP\linkedlist.cpp:8:1: note: candidates are: node::node()
..\CPP\linkedlist.cpp:8:1: note:                 node::node(const node&)

现在,我是编码方面的新手,当我在搜索这个问题时,我发现必须构造一个默认构造函数。 我知道如何创建构造函数,但不创建成员初始化列表构造函数。

这是使用C ++ 11修复的完全损坏的代码。 它仍然会在退出时泄漏内存(您永远不会删除节点),但是:

#include <iostream>

using namespace std;

struct node
{
    node(int a)
    : a(a)
    , ptr(nullptr)
    {}

    int a;
    node *ptr;
};

node* head = nullptr;

void create(int d)
{
    if (head == nullptr)
    {
        head = new node(d);
    }
    else
    {
        node* last = head;
        while (last->ptr != nullptr)
        {
            last = last->ptr;
        }
        last->ptr = new node(d);
    }
}

void display()
{
    node* temp = head;
    while (temp != nullptr)
    {
        cout << temp->a << " --> ";
        temp = temp->ptr;
    }
    cout << endl;
}

int main()
{
    create(5);
    create(6);
    create(8);
    display();
    return 0;
}

请注意,g ++需要-std = c ++ 11来编译代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM