C++ C++;关于函数参数和递归的类和默认值的问题
我需要使用递归来计算链表中的节点C++ C++;关于函数参数和递归的类和默认值的问题,c++,visual-c++,recursion,count,C++,Visual C++,Recursion,Count,我需要使用递归来计算链表中的节点 unsigned CLL::CountNodes(CNode* val) { if(!val) return 0; else return 1 + CountNodes(val->next); } 因此,当我想计算链表中的节点时,比如说,从另一个函数,我会: int main() { CLL list(); cout << list.CountNodes(list.head);
unsigned CLL::CountNodes(CNode* val)
{
if(!val)
return 0;
else
return 1 + CountNodes(val->next);
}
因此,当我想计算链表中的节点时,比如说,从另一个函数,我会:
int main()
{
CLL list();
cout << list.CountNodes(list.head);
}
但这不起作用,因为头部不是静止的。那么使head保持静态是一个问题,因为我必须在类外声明它
有没有办法解决这个问题?
e、 g.cout您可以拥有一个公共函数
int CountNodes()
,该函数使用this->head
调用私有int CountNodes(CNode*)
方法
// in class CLL
public:
unsigned int CountNodes()
{
return CountNodes(head);
}
private:
CNode* head;
unsigned int CountNodes(CNode* val)
{
if(!val)
return 0;
else
return 1 + CountNodes(val->next);
}
现在您有了更好的封装,您的头数据成员是私有的,并且您的客户机代码可以变得更简单
int main()
{
CLL list();
cout << list.CountNodes();
}
intmain()
{
CLL列表();
cout您可以拥有一个公共函数int CountNodes()
,该函数使用this->head
调用私有int CountNodes(CNode*)
方法
// in class CLL
public:
unsigned int CountNodes()
{
return CountNodes(head);
}
private:
CNode* head;
unsigned int CountNodes(CNode* val)
{
if(!val)
return 0;
else
return 1 + CountNodes(val->next);
}
现在您有了更好的封装,您的头数据成员是私有的,并且您的客户机代码可以变得更简单
int main()
{
CLL list();
cout << list.CountNodes();
}
intmain()
{
CLL列表();
CUT< P>使用2个函数。第一个是写的,一个是没有参数的,第一个用“头”作为参数。< /P> < P>使用2个函数。第一个写的,加上没有参数的,第一个用“头”作为参数。C++中的 < P>总是有一个方法。你可以有两个,例如:
unsigned CountNodes (CNode* val)
{
return val ? CountNodes(val->next) + 1 : 0;
}
unsigned CountNodes ()
{
return CountNodes (head);
}
我还建议使用unsigned CountNodes(CNode*val)
函数,因为它不需要CLL
类中的任何内容,也不需要unsigned CountNodes()
,因为它不会更改对象的状态
顺便说一下,C++中有一个使生活更容易,代码更可读,甚至可以使它更快。
if(!val)
return 0;
else
return 1 + CountNodes(val->next);
…你可以这样写:
return val ? 1 + CountNodes(val->next) : 0;
<>在C++中总是有一种方法。你可以有两个,例如:
unsigned CountNodes (CNode* val)
{
return val ? CountNodes(val->next) + 1 : 0;
}
unsigned CountNodes ()
{
return CountNodes (head);
}
我还建议使用unsigned CountNodes(CNode*val)
函数,因为它不需要CLL
类中的任何内容,也不需要unsigned CountNodes()
,因为它不会更改对象的状态
顺便说一下,C++中有一个使生活更容易,代码更可读,甚至可以使它更快。
if(!val)
return 0;
else
return 1 + CountNodes(val->next);
…你可以这样写:
return val ? 1 + CountNodes(val->next) : 0;
谢谢您的提问,欢迎来到Stack Overflow!谢谢您的提问,欢迎来到Stack Overflow!