我正在创建并显示一个单链表。但是,main函数中有一个错误
对‘node::node()’的调用没有匹配的函数
以下是我的代码:
#include <iostream.h>
using namespace std;
class node
{
node *next,*start,*ptr;
int data;
public:
node(int d)
{
data=d;
next=NULL;
start=NULL;
ptr=NULL;
}
void create();
void display();
};
void node::create()
{
int d;
char ch;
node *temp;
do
{
cout<<"Enter data";
cin>>d;
temp=new node(d);
if(start==NULL)
{
start=temp;
}
else
{
ptr=start;
while(ptr->next!=NULL)
{
ptr=ptr->next;
}
ptr->next=temp;
temp->next=NULL;
}
cout<<"\nDo you want to enter more data?";
cin>>ch;
}while(ch=='y'||ch=='Y');
}
void node::display()
{
ptr=start;
while(ptr->next!=NULL)
{
cout<<"\n"<<ptr->data;
ptr=ptr->next;
}
cout<<"\n"<<ptr->data;
}
int main()
{
node n;
int c;
char a;
do
{
cout<<"*****MENU*****";
cout<<"\n1.Create \n2.Display";
cout<<"\nEnter your choice";
cin>>c;
switch(c)
{
case 1:
n.create();
break;
case 2:
n.display();
break;
default:
cout<<"\nInvalid choice";
break;
}
cout<<"\nDo you want to continue?";
cin>>a;
}while(a=='y'||a=='Y');
return 0;
}
当我使用node的朋友类编写相同的程序时,程序成功执行。为什么我们需要使用多个类?
发布于 2015-08-01 11:45:02
对于您的类node
,您只定义了一个构造函数,它接受参数类型int
,这意味着您可以使用这样的参数构造此类的实例,就像您在这里所做的那样:
temp=new node(d); // fine, you pass int d to construct node
但在main()
中,您尝试创建不带任何参数的类node
的实例:
int main()
{
node n; // <---- problem
因此,要么在main()
中创建n
时传递integer,要么为类node
定义另一个不带任何参数构造函数(也称为默认构造函数)。
https://stackoverflow.com/questions/31757860
复制相似问题