重载下标运算符不返回指针



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


这是我对该函数的类减速:

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;
}  

我得到的错误是:

错误:无法在递归调用中将"节点"转换为"节点*"

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

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

无济于事!

我做错了什么?

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

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

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

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

另外,使用 int 作为向量索引的数据类型略有不正确。最好使用std::size_tstd::vector<Node*>::size_type


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

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

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

然后将其用作:

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

最新更新