[英]overload subscript operator does not return pointer
In my class, I have a member variable std::vector<node*>
children 在我的课堂上,我有一个成员变量std::vector<node*>
children
I want to overload the subscript operator so that I can easily index one of the nodes. 我想重载下标运算符,以便我可以轻松索引其中一个节点。
Here is my class deceleration for that function: 这是我的班级减速功能:
node* operator[](int index);
Here is my class definition for that function: 这是我对该函数的类定义:
node* class_name::operator[](int index){
return children[index];
}
However, this function does not seem to return a pointer as I had hoped. 但是,这个函数似乎没有像我希望的那样返回指针。
Here is the function that is giving me trouble: 这是给我带来麻烦的功能:
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;
}
The error I get is: 我得到的错误是:
error: cannot convert 'node' to 'node*' on the recursive call 错误:在递归调用时无法将“node”转换为“node *”
I don't understand why it gives me back a node when I want a pointer to a node. 我不明白为什么当我想要一个指向节点的指针时它会给我一个节点。
Is there something wrong with my overloaded function? 我的重载功能有问题吗?
I tried dereferencing the node in the recursive call: 我尝试在递归调用中取消引用该节点:
Print_Tree(*nptr[i],depth+1);
Print_Tree(*(nptr[i]),depth+1);
Print_Tree(nptr->[i],depth+1);
to no avail! 无济于事!
What am I doing wrong? 我究竟做错了什么?
Your are looking for the problem in the right place, but the syntax in your three correction attempts is still slightly wrong. 您正在寻找正确位置的问题,但三次修正尝试的语法仍然有些错误。
nptr
is a pointer to a Node
object, so you cannot apply the index operator directly (if you do, the compiler will assume it points to the beginning of a Node
array and jump to the ith entry). nptr
是指向Node
对象的指针,因此您无法直接应用索引运算符(如果这样做,编译器将假定它指向Node
数组的开头并跳转到第i个条目)。
Instead you need to first dereference the pointer, and then apply the index operator. 相反,您需要首先取消引用指针,然后应用索引运算符。 Use parentheses to determine the order of this: 使用括号来确定此顺序:
Print_Tree((*nptr)[i],depth+1);
On a separate note, your using int
as the data type for the index into the vector is slightly incorrect. 另外,使用int
作为向量索引的数据类型略有不正确。 Better use std::size_t
or std::vector<Node*>::size_type
. 最好使用std::size_t
或std::vector<Node*>::size_type
。
Furthermore, given that this question is tagged c++11 , I should point out that the correct way to refer to the null pointer is nullptr
, not NULL
. 此外,鉴于这个问题被标记为c ++ 11 ,我应该指出引用空指针的正确方法是nullptr
,而不是NULL
。
Even though it is indeed legal to have operator[]
return a pointer, it is better design (and fits expectations from standard classes) to return a reference instead. 即使让operator[]
返回指针确实合法,但更好的设计(并符合标准类的期望)来返回引用。 You can then take the address of that reference as follows: 然后,您可以按如下方式获取该引用的地址:
node& class_name::operator[](int index){
return *(children[index]);
}
and then use it as: 然后将其用作:
Print_Tree(&(*nptr)[i],depth+1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.