return语句不返回值

时间:2013-09-08 08:18:06

标签: c++

emp* emp::check(string a,emp* ceo)
{
   emp* l;
   employee* b;
   l=ceo;
   if(l->name==a)
   {
    cout<<l->name;
    return l;
   }
   b=l->j;
   while (b!=NULL)
   {
      check(a,b->junior);
      b=b->next;
   }
}

void main()
{
   l = check(d,ceo);
   cout<<l->name;
}

现在最初正在打印l->name的值,但最终main的值l未被返回。
这意味着它已达到return语句,但未返回l 有谁可以解释为什么?

1 个答案:

答案 0 :(得分:3)

这是怎么回事,它在check的一个递归调用中匹配,然后丢弃返回值。您需要将功能更改为如下所示:

emp* emp::check(string a,emp* ceo)
{
   emp* l;
   employee* b;
   l=ceo;
   if(l->name==a)
   {
    cout<<l->name;
    return l;
   }
   b=l->j;
   while (b!=NULL)
   {
      l = check(a,b->junior); // <----- line changed
      if (l)
         return l;            // If we found something, return it. 
      b=b->next;
   }

   return 0; // <----- Always return a value
}

此外,您的代码存在各种风格问题,如果您进行类似的更改以使您的变量和函数名称有用,则会更清楚:

emp* emp::findEmployeeByName(string name,emp* root)
{
   if(root->name==a)
   {
    cout<<root->name;
    return root;
   }

   // What on earth is ->j? Give your members meaningful names
   for (employee* worker=l->j; worker; worker = worker->next)
   {
      emp* match = findEmployeeByName(name,worker->junior); // <----- line changed
      if (match)
         return match;            // If we found something, return it. 
   }

   return 0; // <----- Always return a value
}