错误C3861:'rollDice':找不到标识符

时间:2013-04-30 01:29:35

标签: c++ visual-studio-2010 visual-studio-2012 mfc

我正在尝试实现一些图形,但我无法调用最底部显示的函数int rollDice(),我不知道如何解决这个问题?任何想法......我收到错误错误C3861:'rollDice':找不到标识符。

int rollDice();

    void CMFCApplication11Dlg::OnBnClickedButton1()
{ 

   enum Status { CONTINUE, WON, LOST }; 
   int myPoint; 
   Status gameStatus;  
   srand( (unsigned)time( NULL ) ); 
   int sumOfDice = rollDice();

   switch ( sumOfDice ) 
   {
      case 7: 
      case 11:  
        gameStatus = WON;
        break;

      case 2: 
      case 3: 
      case 12:  
        gameStatus = LOST;
        break;
      default: 
            gameStatus = CONTINUE; 
            myPoint = sumOfDice;  
         break;  
   } 
   while ( gameStatus == CONTINUE )
   { 
      rollCounter++;  
      sumOfDice = rollDice(); 

      if ( sumOfDice == myPoint ) 
         gameStatus = WON;
      else
         if ( sumOfDice == 7 ) 
            gameStatus = LOST;
   } 


   if ( gameStatus == WON )
   {  

   }
   else
   {   

   }
} 

int rollDice() 
{
   int die1 = 1 + rand() % 6; 
   int die2 = 1 + rand() % 6; 
   int sum = die1 + die2; 
   return sum;
} 

更新

2 个答案:

答案 0 :(得分:27)

编译器从头到尾遍历您的文件,这意味着您的函数定义的位置很重要。在这种情况下,您可以在第一次使用此函数之前移动该函数的定义:

void rollDice()
{
    ...
}

void otherFunction()
{
    // rollDice has been previously defined:
    rollDice();
}

或者您可以使用转发声明告诉编译器存在这样的函数:

// function rollDice with the following prototype exists:
void rollDice();

void otherFunction()
{
    // rollDice has been previously declared:
    rollDice();
}

// definition of rollDice:
void rollDice()
{
    ...
}

另请注意,函数原型由 name 指定,但返回值参数

void foo();
int foo(int);
int foo(int, int);

这就是函数识别的方式。 int foo();void foo();是不同的函数,但由于它们的返回值不同,因此它们不能存在于同一范围内(有关详细信息,请参阅Function Overloading)。

答案 1 :(得分:3)

放置函数rollDice

的声明
 int rollDice();
OnBnClickedButton1之前

或只是在rollDice之前移动OnBnClickedButton1函数的定义。

当您在rollDice内调用OnBnClickedButton1时,原因在于当前代码,编译器尚未看到该函数,这就是您看到identifier not found错误的原因。