我正在尝试实现一些图形,但是在调用最底部显示的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;
}
更新
最佳答案
编译器从头到尾遍历文件,这意味着函数定义的位置很重要。在这种情况下,您可以在第一次使用此功能之前将其定义移开:
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();
是不同的函数,但是由于它们的返回值不同,因此它们不能存在于同一范围内(有关更多信息,请参见Function Overloading)。关于c++ - 错误C3861:“rollDice”:找不到标识符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41498082/