首页 > 解决方案 > 为什么会有一个指向未指定模板类的对象的指针(没有指定使用的实际类型)?

问题描述

我有一个与我在二叉树上做的练习有点相关的问题。我们已经给出了一些代码,而该代码引发了我的问题。

template <typename nodetype> class node {
public:
    //some functions like constructor and getData() etc.
private:
    node* leftptr;
    nodetype data;
    node* rightptr;
}

template <typename treetype> class tree {
public:
    //many other functions
    insertNode(treetype &value) {
        insertNodeHelper(rootptr, value);
    }
    insertNodeHelper(node<treetype>* & curptr, treetype &value) {
        //recursive function that compares value-parameter to curptr-node-value, then goes either left or right one node deeper, or if you cant to go deeper left or right, creates new node where you are) 
    }
private:
    node<nodetype>* rootptr;
}

在树模板的 insertNodeHelper 函数的参数列表中,它显示“node< treetype >* curptr”。我发现包含 treetype-specification(1) 是合乎逻辑的,因为没有类“节点”,所以永远不会有此类的对象,因此也没有指向任何此类对象的指针,对吗?
但是我不明白为什么在节点类本身的数据元素中不需要任何这样的规范(例如,它说node* leftptr而不是node< nodetype > *leftptr)?因为您在编写定义时提到了定义的类组/模板,所以是否只是隐含地假设您的意思是使用任何实际类?(例如,如果模板实际用于 int 类型的类,编译器会自动将“ node* leftptr”更改为“ node<int>* leftptr”)?
提前感谢您的帮助。

(1) treetype-specifier = " node< treetype >* curptr " 的inlucision 而不是 " node* curptr "

标签: c++visual-studiotemplates

解决方案


推荐阅读