C++关于函数参数和递归的类和默认值的问题
我需要使用递归来计算链表中的节点。
unsigned CLL::CountNodes(CNode* val)
{
if(!val)
return 0;
else
return 1 + CountNodes(val->next);
}
因此,当我想从另一个函数中计算链表中的节点时,我会这样:
int main()
{
CLL list();
cout << list.CountNodes(list.head);
}
但这似乎有点狡猾,因为该类应该能够计算列表,而无需我将一个点传递到链表的头部名单的头。对于 for 循环来说,这看起来很简单;但是,通过递归,我尝试了:
unsigned CLL::CountNodes(CNode* val = head)
{
if(!val)
return 0;
else
return 1 + CountNodes(val->next);
}
但这不起作用,因为 head 不是静态的。然后使 head 静态是一个问题,因为我必须在类之外声明它。
有办法解决这个问题吗? 例如 cout << list.CountNodes(); 或者使用递归时必须始终传入列表的头部?
I need to use recursion to count the nodes in a linked list.
unsigned CLL::CountNodes(CNode* val)
{
if(!val)
return 0;
else
return 1 + CountNodes(val->next);
}
So when I want to count the nodes in the linked list, from say, another function, I go:
int main()
{
CLL list();
cout << list.CountNodes(list.head);
}
This seems a bit dodgy though, because the class should be able to count the list without me passing in a point to the head of the head of the list. This seems straight forward with a for-loop; however, with recursion, I tried:
unsigned CLL::CountNodes(CNode* val = head)
{
if(!val)
return 0;
else
return 1 + CountNodes(val->next);
}
but this did not work because head is not static. Then making head static is a problem, because I have to declare it outside the class.
Is there anyway to solve the problem?
e.g. cout << list.CountNodes();
Or must the head of the list always be passed in when using recursion?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在C++中总有办法。您可能有两个重载的函数,例如:
我还建议使用
unsigned CountNodes (CNode* val)
函数 static 因为它不需要来自CLL
的任何内容类,以及unsigned CountNodes ()
方法常量因为它不会改变对象的状态。顺便说一句,C++ 中有一个三元运算符,它使生活更轻松,代码更具可读性,甚至可能使它更快。因此,
您可以这样写:
In C++ there is always a way. You may have two overloaded functions, for example:
I would also recommend making
unsigned CountNodes (CNode* val)
function static since it doesn't need anything fromCLL
class, andunsigned CountNodes ()
method constant because it doesn't change object's state.And by the way, there is a ternary operator in C++ that makes life easier, code more readable and may even make it faster. So instead of:
... you could write like:
您可以有一个公共函数
int CountNodes()
,它使用this->head
调用私有int CountNodes(CNode*)
方法。现在您有了更好的封装,您的头数据成员是私有的,并且您的客户端代码可以变得更简单。
You could have a public function
int CountNodes()
that calls a privateint CountNodes(CNode*)
method withthis->head
.Now you have better encapsulation has your head data member is private and your client code can be made simpler.
使用2个函数。第一个是书面的,加上一个没有参数的,它调用第一个以“head”作为参数的。
Use 2 functions. The first one as written, plus one with no arguments which calls the first with 'head' as the argument.