2012-06-03 44 views
0

我最近開始學習C++,並在理解模板機制時遇到問題。 該任務首先是構建用戶定義的二叉樹。我無法編譯我的代碼。使用代碼錯誤的模板

#include <iostream> 
using namespace std; 
template <typename DataType> struct TreeNode 
{ 
    TreeNode(DataType val, TreeNode *leftPtr = null, TreeNode *rightPtr = null) 
    { 
     left = leftPtr; 
     right = rightPtr; 
     data = val; 
    } 
    TreeNode *left, *right; 
    DataType data; 
}; 
template <typename DataType> TreeNode *BuildTree() 
{ 
    TreeNode *root = new TreeNode(10, new TreeNode(20), new TreeNode(30)); 

    TreeNode *curRoot = root; 
    curRoot = curRoot->left; 
    curRoot->left = new TreeNode(40); 
    curRoot->left->left = new TreeNode(70); 
    curRoot->right = new TreeNode(50); 
    curRoot = curRoot->right; 
    curRoot->left = new TreeNode(80, new TreeNode(100), new TreeNode(110)); 
    curRoot = root->right; 
    curRoot->left = new TreeNode(60); 
    curRoot = curRoot->left; 
    curRoot->right = new TreeNode(90, new TreeNode(120), new TreeNode(130)); 

    return root; 
} 
int main() 
{ 
    TreeNode *treeRoot = BuildTree<int>(); 
    cin.get(); 
    return 0; 
} 

功能BuildTree建立樹的具體實例,具體數據類型。請幫我理解我的錯誤。 請不要留意使用後我沒有釋放記憶的事實。這只是一個草稿。

+4

當問一個問題關於一個編譯問題,你應該總是發佈確切的錯誤信息。 –

回答

4

由於TreeNode是一個模板類,你有當您使用它來指定專業化:

template <typename DataType> TreeNode *BuildTree() 

應該

template <typename DataType> TreeNode<DataType> *BuildTree() 

TreeNode *root = new TreeNode(10, new TreeNode(20), new TreeNode(30)); 

應該

TreeNode<DataType> *root = new TreeNode(10, new TreeNode(20), new TreeNode(30)); 

等人的方法,再加上main:中

TreeNode<int> *treeRoot = BuildTree<int>(); 

代替

TreeNode *treeRoot = BuildTree<int>(); 
+0

不是這樣的:'TreeNode * root = new TreeNode (10,new TreeNode (20),new TreeNode (30));'? – Ruben

+0

非常感謝,你幫了我很多! –

0

我覺得你的代碼應該是這樣的:

#include <iostream> 
using namespace std; 
template <typename DataType> struct TreeNode 
{ 
    TreeNode(DataType val, TreeNode<DataType> *leftPtr = null, TreeNode<DataType> *rightPtr = null) 
    { 
     left = leftPtr; 
     right = rightPtr; 
     data = val; 
    } 
    TreeNode<DataType> *left, *right; 
    DataType data; 
}; 
template <typename DataType> TreeNode<DataType> *BuildTree() 
{ 
    TreeNode<DataType> *root = new TreeNode(10, new TreeNode<DataType>(20), new TreeNode<DataType>(30)); 

    TreeNode<DataType> *curRoot = root; 
    curRoot = curRoot->left; 
    curRoot->left = new TreeNode<DataType>(40); 
    curRoot->left->left = new TreeNode<DataType>(70); 
    curRoot->right = new TreeNode<DataType>(50); 
    curRoot = curRoot->right; 
    curRoot->left = new TreeNode<DataType>(80, new TreeNode<DataType>(100), new TreeNode<DataType>(110)); 
    curRoot = root->right; 
    curRoot->left = new TreeNode<DataType>(60); 
    curRoot = curRoot->left; 
    curRoot->right = new TreeNode<DataType>(90, new TreeNode<DataType>(120), new TreeNode<DataType>(130)); 

    return root; 
} 
int main() 
{ 
    TreeNode<int> *treeRoot = BuildTree<int>(); 
    cin.get(); 
    return 0; 
}