64,648
社区成员
发帖
与我相关
我的任务
分享
拿到一个.h文件里还报错?
就像我六楼代码一样?
我六楼代码可没错!
模板的定义和实现支持不好~~~
最好别分开!
.h:
#ifndef CLASSDEF
#define CLASSDEF
#include <iostream>
using namespace std;
template <class type> class SingleLink;
template <class T>
class Node
{
public:
friend class SingleLink <T>;
T data;
Node *Next;
};
template <class type>
class SingleLink
{
public:
SingleLink();
virtual ~SingleLink();
bool insert(type Element);//在当前位置插入值
private:
Node <type> *pHead,*pCurNode,*ptemp;
};
//#include"mycpp.cpp"
template <class type>
SingleLink <type>::SingleLink()
{//creat a head node
pHead = pCurNode = ptemp = new Node <type>;
pHead->Next = NULL;
}
template <class type>
SingleLink <type>::~SingleLink()
{
pCurNode = pHead;
while(pCurNode)
{
pHead = pHead->Next;
delete pCurNode;
pCurNode = pHead;
}
}
template <class type>
bool SingleLink <type>::insert(type element)
{//insert the element into current position
if(!pCurNode)
return false;//no link because no head node
else// insert the element into current position
{
ptemp = pCurNode->Next;
pCurNode = pCurNode->Next = new Node <type>;
pCurNode->data = element;
pCurNode->Next = ptemp;
}
return true;
}
#endif
main.cpp
#include "head.h"
int main(int argc, char* argv[])
{
int a[5] = {1,2,3,4,5};
SingleLink <int> linklist;
for(int i = 0; i < 5; i++)
{
linklist.insert(a[i]);
}
return 0;
}
你以前写的是:
pHead = pCurNode = ptemp = new Node <Type>;
帮你查了一下;
http://topic.csdn.net/u/20071026/15/fad0132c-692a-4c61-8e87-0bfabd0beba4.html
http://www.cnblogs.com/chio/archive/2007/09/08/886390.html
我试了一下,不是很好使~~
http://hi.baidu.com/beckbeckham/blog/item/24bff8454527d73886947317.html
还有啊:
#include "SingleLink.cpp"
这不在.cpp里这么用
如果要实现模板类的定义和实现分离,可以在类定义的头文件末尾加上:
#include "SingleLink.cpp"
当然,这只是在vc6.0下能行,其他编译器,不敢说!
#include <iostream>
using namespace std;
template <class type> class SingleLink;
template <class T>
class Node
{
public:
friend class SingleLink <T>;
T data;
Node *Next; //这里直接Node就行!
};
template <class type>
class SingleLink
{
public:
SingleLink();
virtual ~SingleLink();
bool insert(type Element);//在当前位置插入值
private:
Node <type> *pHead,*pCurNode,*ptemp;
};
template <class type>
SingleLink <type>::SingleLink()
{//creat a head node
pHead = pCurNode = ptemp = new Node <type>; //这里写错了!!
pHead->Next = NULL;
}
template <class type>
SingleLink <type>::~SingleLink()
{
pCurNode = pHead;
while(pCurNode)
{
pHead = pHead->Next;
delete pCurNode;
pCurNode = pHead;
}
}
template <class type>
bool SingleLink <type>::insert(type element)
{//insert the element into current position
if(!pCurNode)
return false;//no link because no head node
else// insert the element into current position
{
ptemp = pCurNode->Next;
pCurNode = pCurNode->Next = new Node <type>;
pCurNode->data = element; //这里没有data
pCurNode->Next = ptemp;
}
return true;
}
int main(int argc, char* argv[])
{
int a[5] = {1,2,3,4,5};
SingleLink <int> linklist;
for(int i = 0; i < 5; i++)
{
linklist.insert(a[i]);
}
return 0;
}