"bool"之前的预期主要表达式

expected primary expression before 'bool'

本文关键字:表达式 bool      更新时间:2023-10-16

我的程序在主函数下的函数调用repeatOrNot (bool);上显示"错误:'bool'之前的预期主表达式"。这是为什么呢?

bool fiveOrNot(); 
void repeatOrNot (bool);
int main()
{
    fiveOrNot();
    repeatOrNot (bool);
    return 0;
}
bool fiveorNot()
{
    int number;
    cout << "Enter any number except for 5.n";
    cin >> number;
    if(number == 5)
        return true;
    else
        return false;
}
void repeatOrNot(bool repeat)
{
    if(repeat == true)
        fiveorNot();
    else
        cout << ":(n";
}

在C++中,有所谓的形式参数实际参数。当你定义一个函数时,你正在处理形式参数,这意味着你应该只指定参数的类型,并且(如果你愿意)给它一些有意义的全名

void repeatOrNot(bool repeat)//<----"repeat" is a formal parameter. 
//You are not passing anything to the function, 
//you are just telling the compiler that this function accepts one argument 
//of a bool type.
{
    if(repeat == true)
        fiveorNot();
    else
        cout << ":(n";
}

但是,当您调用函数时,您需要向其传递一个实际参数,即某种正确类型的变量。在您的情况下,您可能打算将调用的结果传递给fiveOrNot函数。你可以这样做:

bool isFive = fiveOrNot();
repeatOrNot (isFive);//<---This is an actual parameter.
//here you are really passing a variable to your function.

或者像这样:

repeatOrNot(fiveOrNot());//<--the result of the execution of "fiveOrNot" will be passed into "repeatOrNot"