I know this is probably a first year question, but I'm having some problems with templates and I haven't found a suitable answer yet. I'm trying to instantiate a new templated class like so:
TreeNode <T>newLeft = new TreeNode(root->data[0]);
Which is refering to a constructor which looks like:
template <class T>
//paramerter receving constructor
TreeNode<T>::TreeNode(T item){
data[0] = item;
nodeType = 2;
}//end
And I'm getting the following errors:
error: expected type-specifier before ‘TreeNode’ error: expected `;' before ‘TreeNode’What is the type-specifier? I can provide more code if necessary, and I know I asked a question about this code earlier, and I'm sure I'll get flamed for it; but I still have questions...
edit: Here's the function it's used in:
template <class T>
void TwoThreeFourTree<T>::splitRoot(){
TreeNode <T> newRoot;
newRoot = new TreeNode(root->data[1]);
TreeNode <T>newLeft = new TreeNode(root->data[0]);
TreeNode <T>newRight = new 开发者_如何学GoTreeNode(root->data[2]);
newRoot.child[0] = newLeft;
newRoot.child[1] = newRight;
newLeft.child[0] = root.child[0];
newLeft.child[1] = root.child[1];
newRight.child[0] = root.child[2];
newRight.child[1] = root.child[3];
root = newRoot;
}
And I get the same two errors each time I try to create a new object in the function
You forgot T
in new
, and pointers:
TreeNode<T>* newRoot;
newRoot = new TreeNode<T>(root->data[1]);
Note, you'll need to fix your usage of pointers everywhere, not just here. Remember that this isn't Java or C#, and a variable of type TreeNode<T>
is not a reference to T
- it is a T. And to build a tree, you need references - that is, pointers. Though you may also want to consider using std::auto_ptr
here to guarantee cleanup.
精彩评论