错误:"char"之前的预期主表达式

error: expected primary-expression before 'char'

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

尝试在int main中调用函数bool yes()。继续得到上面显示的错误。我应该在函数调用中包含char c吗?

bool yes(char c){ 
if(c == 'y' || c == 'Y'){
    return true;
}
else 
    return false;
}
int main(){
try{
char c;
cin>>c;
bool yes(char c); //not sure if char c should be here
    cout<<"Think of one of these 8 things: ..... Press '|' when you are readyn";
if(c == '|'){
    cout<<"Are you thinking of something big?n";
    cin>>c;
    if(yes(char c) == true){ //error here in yes(), trying to call function
        cout<<"Are you thinking of something that is alive?n";
        cin>>c;
        if(yes(char c) == true){ //error here in yes(), trying to call function
            cout<<"Are you thinking of an animal?n";
            cin>>c;
                 if(yes(char c) == true){ //error here in yes(), trying to call function
                    cout<<"You are thinking of an elephant.n";
                    }
            }
        }
}

调用"yes"函数的方式存在一些小的语义问题。试试这个:

bool yesResult = yes(c);

在调用该方法时不包含"char"是正确的。当您将c传递给函数调用时,就不再需要它了——c本质上是一个char。另一件需要注意的事情是,在第一次调用yes()时,在调用之前指定了"bool"。只有当您想存储函数的返回值时,才需要这样的语法,如我的示例所示。请注意,该类型需要附带一个名称。if语句条件中的yes()的其他调用完全正常。