错误并非所有控制路径都返回一个值

时间:2014-11-24 03:51:21

标签: controls overloading return-value

我的编译器说并非所有控制路径都返回一个值,而是指向一个重载的>>变量函数。我不确定是什么导致了这个问题,任何帮助将不胜感激。我试图重载流提取操作符以定义输入是否有效。如果不是,则应设置一个failbit来指示输入不正确。

 std::istream &operator >> (std::istream &input, ComplexClass &c)//overloading        extraction operator
     {
         int number;
         int multiplier;
         char temp;//temp variable used to store input


         input >> number;//gets real number

         // test if character is a space 
         if (input.peek() == ' ' /* Write a call to the peek member function to
                                 test if the next character is a space ' ' */) // case    a + bi 
         {
             c.real = number;
             input >> temp;

             multiplier = (temp == '+') ? 1 : -1;
         }
             // set failbit if character not a space 
         if (input.peek() != ' ')
         {
             /* Write a call to the clear member function with
             ios::failbit as the argument to set input's fail bit */
             input.clear(ios::failbit);
         }
        else

                 // set imaginary part if data is valid 
            if (input.peek() == ' ')
            {
                input >> c.imaginary;
                c.imaginary *= multiplier;
                input >> temp;
            }
            if (input.peek() == '\n' /* Write a call to member function peek to test if the next
                                              character is a newline \n */) // character not a newline 
            {
              input.clear(ios::failbit); // set bad bit 
            } // end if 
            else
            {
                     input.clear(ios::failbit); // set bad bit 
            } // end else 
          // end if 
         if (input.peek() == 'i' /* Write a call to member function peek to test if
                                      the next character is 'i' */) // test for i of         imaginary number 
         {
             input >> temp;

             // test for newline character entered 
             if (input.peek() == '\n')
             {
                 c.real = 0;
                 c.imaginary = number;
             } // end if 

             else if (input.peek() == '\n') // set real number if it is valid 
             {
                 c.real = number;
                 c.imaginary = 0;
             } // end else if 
             else
             {
                 input.clear(ios::failbit); // set bad bit 

             }


             return input;
         }
     }

1 个答案:

答案 0 :(得分:0)

return语句只在最后一个if:

中执行
if (input.peek() == 'i' ) {
    ...
    return input;
}

应该改为:

if (input.peek() == 'i' ) {
    ...
}
return input;