该程序是使用模板链接列表。
#include
using namespace std;
template
class link
{
struct node
{
T data;
struct node * next;
}*p;
public:
link();
void addatbeg(T);
void show();
void rematbeg();
void addatmid(T,T);
};
template
link::link()
{
p=NULL;
}
template
void link::show()
{
node*q=p;
while(q->next!=NULL)
{
cout<data;
cout<";
q=q->next;
}
cout<data<
}
template
void link::addatbeg(T a)
{
node *temp;
temp=(node*)malloc(sizeof(node));
temp->data=a;
temp->next=NULL;
if(p==NULL)
{
p=temp;
}
else
{
temp->next=p;
p=temp;
}
}
template
void link::rematbeg()
{
if(p==NULL)
cout<
else
p=p->next;
}
template
void link::addatmid(T a,T b)
{
node* temp,*q;
temp=(node*)malloc(sizeof(node));
temp->data=b;
temp->next=NULL;
q=p;
if(p==NULL)
cout<
else
{
while(q->data!=a)
q=q->next;
}
temp->next=q->next;
q->next=temp;
}
int main()
{
link l1;
l1.addatbeg(2);
l1.addatbeg(3);
l1.addatbeg(4);
l1.addatbeg(5);
l1.addatmid(3,9);
l1.show();
l1.rematbeg();
l1.show();
}同样的程序在windows 7 dev C++编译器上运行良好,而在linux g ++编译器中它提供了以下错误。
pllab52.cpp:4:7: error: ‘template struct link’ redeclared as different kind of symbol
/usr/include/unistd.h:809:12: error: previous declaration of ‘int link(const char*, const char*)’
pllab52.cpp:20:1: error: ‘link’ does not name a type
pllab52.cpp:25:10: error: expected initializer before ‘
pllab52.cpp:37:10: error: expected initializer before ‘
pllab52.cpp:54:10: error: expected initializer before ‘
pllab52.cpp:62:10: error: expected initializer before ‘
pllab52.cpp: In function ‘int main()’:
pllab52.cpp:81:10: error: expected primary-expression before ‘int’
pllab52.cpp:81:10: error: expected ‘;’ before ‘int’
pllab52.cpp:82:5: error: ‘l1’ was not declared in this scope两种C++程序的行为都不相同。是因为两者有不同的编译器或什么?请告诉解决方案来解决这个问题。请解释何时会出现这些问题。我也测试了其他程序,但没有遇到这样的问题。请帮帮我。提前致谢。
我在程序中的每个地方都改变了链接link1。现在我得到了一个新的错误,下面给出。 b>
pllab52.cpp: In member function ‘void link1::addatbeg(T)’:
pllab52.cpp:40:37: error: there are no arguments to ‘malloc’ that depend on a template parameter, so a declaration of ‘malloc’ must be available [-fpermissive]
pllab52.cpp:40:37: note: (if you use ‘-fpermissive’, G++ will accept your code, but allowing the use of an undeclared name is deprecated)
pllab52.cpp: In member function ‘void link1::addatmid(T, T)’:
pllab52.cpp:65:37: error: there are no arguments to ‘malloc’ that depend on a template parameter, so a declaration of ‘malloc’ must be available [-fpermissive]
pllab52.cpp: In member function ‘void link1::addatbeg(T) [with T = int]’:
pllab52.cpp:82:18: instantiated from here
pllab52.cpp:40:6: error: ‘malloc’ was not declared in this scope
pllab52.cpp: In member function ‘void link1::addatmid(T, T) [with T = int]’:
pllab52.cpp:86:20: instantiated from here
pllab52.cpp:65:6: error: ‘malloc’ was not declared in this scope