6

在我的班级中,我有一个成员变量std::vector<node*>children
我想重载下标运算符,以便我可以轻松地索引其中一个节点。


这是我对该功能的类减速:

node* operator[](int index);  

这是我对该函数的类定义:

node* class_name::operator[](int index){

    return children[index];
}  

然而,这个函数似乎并没有像我希望的那样返回一个指针。
这是给我带来麻烦的功能:

void Print_Tree(node* nptr, unsigned int & depth){

    if (NULL == nptr) {
        return;
    }
      //node display code

    for (int i = 0; i < nptr->Number_Of_Children(); ++i){
        Print_Tree(nptr[i],depth+1); //<- Problem Here!
    }
     //node display code

    return;
}  

我得到的错误是:

错误:无法在递归调用中将“node”转换为“node*”

我不明白为什么当我想要一个指向节点的指针时它会给我一个节点。
我的重载函数有问题吗?
我尝试在递归调用中取消引用节点:

Print_Tree(*nptr[i],depth+1);  
Print_Tree(*(nptr[i]),depth+1);
Print_Tree(nptr->[i],depth+1);

无济于事!

我究竟做错了什么?

4

2 回答 2

8

您正在正确的位置寻找问题,但是您的三次更正尝试中的语法仍然略有错误。

nptr是指向Node对象的指针,因此您不能直接应用索引运算符(如果这样做,编译器将假定它指向Node数组的开头并跳转到第 i 个条目)。

相反,您需要首先取消引用指针,然后应用索引运算符。使用括号来确定它的顺序:

Print_Tree((*nptr)[i],depth+1);

在单独的说明中,您将int其用作向量索引的数据类型略有不正确。更好地使用std::size_tstd::vector<Node*>::size_type.


此外,鉴于这个问题被标记为,我应该指出,引用空指针的正确方法是nullptr,而不是NULL

于 2012-09-16T07:31:07.073 回答
1

尽管返回指针确实是合法operator[]的,但更好的设计(并且符合标准类的期望)改为返回引用。然后,您可以按如下方式获取该参考的地址:

node& class_name::operator[](int index){
    return *(children[index]);
}

然后将其用作:

Print_Tree(&(*nptr)[i],depth+1);
于 2012-09-17T01:25:12.693 回答