如何申请C++模板类型的存储空间
程序代码:
#ifndef BINARYTREE #define BINARYTREE template <typename T> struct TreeNode { TreeNode(T a=0):data(a),lchild(0),rchild(0){} T data; TreeNode<T> *lchild,*rchild; }; #endif
程序代码:
#include<iostream> #include<vector> using namespace std; //----------------------------------------------------- #include"Tree.h" TreeNode<int> *previousVisitNode; void flatten(TreeNode<int> *root) { if(!root) return; TreeNode<int> *right=root->rchild; if(previousVisitNode!=0) { previousVisitNode->rchild=0; previousVisitNode->lchild=root; } previousVisitNode=root; flatten(root->lchild); flatten(right); } //----------------------------------------------------- TreeNode<int>* CreatBinaryTree(vector<int> a)//建立二叉排序树 { if(a.empty()) return 0; TreeNode<int> *p,*q,*root=0; for(int i=0;i<a.size();i++) { if(root==0) { p=new TreeNode;//这儿 p->data=a[i]; p->lchild=0;p->rchild=0; root=p; } else { p=new TreeNode;//还有这儿 p->data=a[i]; p->lchild=0;p->rchild=0; TreeNode<int> *pre; while(q) { if(p->data>q->data) { pre=q;q=q->rchild; } else if(p->data<q->data) { pre=q;q=q->lchild; } else break; } if(q!=0) continue; if(p->data>pre->data) pre->rchild=p; else pre->lchild=p; } q=root; } return root; } int main() { int a[]={5,4,3,2,1,6,7,8,9}; vector<int> num(a,a+9); TreeNode<int> *r=CreatBinaryTree(num); flatten(r); for(TreeNode<int> *p=r;p;p=p->lchild) cout <<p->data<<" "; cout<<endl; return 0; }
E:\练习题\二叉树扁平化\Cpp2.cpp(29) : error C2955: 'TreeNode' : use of class template requires template argument list
e:\练习题\二叉树扁平化\tree.h(9) : see declaration of 'TreeNode'
E:\练习题\二叉树扁平化\Cpp2.cpp(29) : error C2955: 'TreeNode' : use of class template requires template argument list
e:\练习题\二叉树扁平化\tree.h(9) : see declaration of 'TreeNode'
E:\练习题\二叉树扁平化\Cpp2.cpp(29) : error C2512: 'TreeNode' : no appropriate default constructor available
E:\练习题\二叉树扁平化\Cpp2.cpp(36) : error C2955: 'TreeNode' : use of class template requires template argument list
e:\练习题\二叉树扁平化\tree.h(9) : see declaration of 'TreeNode'
E:\练习题\二叉树扁平化\Cpp2.cpp(36) : error C2955: 'TreeNode' : use of class template requires template argument list
e:\练习题\二叉树扁平化\tree.h(9) : see declaration of 'TreeNode'
E:\练习题\二叉树扁平化\Cpp2.cpp(36) : error C2512: 'TreeNode' : no appropriate default constructor available
执行 cl.exe 时出错.
Cpp2.exe - 1 error(s), 0 warning(s)
不懂如何申请模板的动态空间,另外我不是很确定结构体模板是不是真正确的,求相告。
[此贴子已经被作者于2018-1-13 10:52编辑过]