gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:16:16 25 4
gpt4 key购买 nike

在我的类中,我有一个成员变量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;
}

我得到的错误是:

error: cannot convert ‘node’ to ‘node*’ on the recursive call

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

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

没用!

我做错了什么?

最佳答案

你在正确的地方寻找问题,但你的三次更正尝试中的语法仍然有点错误。

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

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

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

另外,您使用的是 int因为 vector 索引的数据类型稍微不正确。更好用std::size_tstd::vector<Node*>::size_type .


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

关于c++ - 重载下标运算符不返回指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12445103/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com