该程序适用于使用模板的链表。
#include<iostream>
using namespace std;
template <class T>
class link
{
struct node
{
T data;
struct node * next;
}*p;
public:
link();
void addatbeg(T);
void show();
void rematbeg();
void addatmid(T,T);
};
template <class T>
link<T>::link()
{
p=NULL;
}
template <class T>
void link<T>::show()
{
node*q=p;
while(q->next!=NULL)
{
cout<<q->data;
cout<<"->";
q=q->next;
}
cout<<q->data<<"\n";
}
template <class T>
void link<T>::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 <class T>
void link<T>::rematbeg()
{
if(p==NULL)
cout<<"Link List is Empty\n";
else
p=p->next;
}
template <class T>
void link<T>::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<<"\n Link List is Empty\n"<<endl;
else
{
while(q->data!=a)
q=q->next;
}
temp->next=q->next;
q->next=temp;
}
int main()
{
link<int> 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<class T> 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 ‘<’ token
pllab52.cpp:37:10: error: expected initializer before ‘<’ token
pllab52.cpp:54:10: error: expected initializer before ‘<’ token
pllab52.cpp:62:10: error: expected initializer before ‘<’ token
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。现在我收到一个新错误,如下所示。
pllab52.cpp: In member function ‘void link1<T>::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<T>::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<T>::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<T>::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