8

I am trying implement some graphics, but I am having trouble calling the function int rollDice() shown on the very bottom and am not sure how to solve this? any ideas... I am getting an error error C3861: 'rollDice': identifier not found.

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;
} 

updated

4

2 回答 2

30

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

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()
{
    ...
}

另请注意,函数原型是由名称指定的,但也有返回值参数

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

这就是区分功能的方式。int foo();void foo();是不同的函数,但是由于它们仅在返回值上有所不同,因此它们不能存在于同一范围内(有关更多信息,请参阅函数重载)。

于 2013-04-30T01:40:40.163 回答
3

放函数声明rollDice

 int rollDice();

beforeOnBnClickedButton1或只是将rollDice函数的定义移到 before OnBnClickedButton1

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

于 2013-04-30T01:40:21.867 回答