【发布时间】:2012-09-08 20:00:33
【问题描述】:
在我的课堂上,我有一个成员变量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);
无济于事!
我做错了什么?
【问题讨论】:
-
(*nptr)[i]应该可以解决问题。问题是您将operator[]定义为在node类上工作,而不是在指向node的指针上工作。当你说nptr[i]时,你调用的是内置的operator[]。 -
哦!现在非常明显。谢谢
标签: c++ class pointers c++11 operator-overloading