【问题标题】:error: expected primary-expression before 'char'错误:“char”之前的预期主表达式
【发布时间】:2014-11-30 06:54:00
【问题描述】:

试图在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 ready\n";

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

                    }
            }
        }
}

【问题讨论】:

  • 阅读任何 C++ 教程并学习如何调用函数。提示:不像yes(char c)
  • try 的目的是什么?另外,if 语句中不需要== true
  • 为了简化,删除这一行:bool yes(char c); -- 在你的例子中没有任何作用。
  • 如前所述,您的函数调用语法是错误的。 if (yes(char c) == true) 应该是 if (yes(c) == true)。最重要的是,没有必要将 bool 的相等值与 falsetrue 进行比较。它已经是一个布尔值;测试一下:if (yes(c))

标签: c++ char boolean


【解决方案1】:

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

bool yesResult = yes(c);

调用方法时不包括“char”是对的。当您将 c 传递给函数调用时不再需要它 - c 本质上是一个字符。需要注意的另一件事是,在您第一次调用 yes() 时,您在调用之前指定了“bool”。仅当您想存储函数的返回值时才需要这种语法,如我的示例所示。请注意,类型需要带有名称。您在 if 语句条件中对 yes() 的其他调用完全没有问题。

【讨论】:

  • 随着c 不断变化,将yes(c) 的结果分配给常量变量没有意义。继续拨打yes(c)
  • 好点。我没有阅读其余的代码。 const 关键字已通过编辑删除。
  • 返回值不需要存储在变量中。直接在 OP 的代码中使用就可以了。
  • 显然不需要。但是,OP 对 yes() 的第一次调用似乎有点混乱,因为它在调用之前不必要地指定了一个类型。我的愿望是在这种语法有效时显示 OP。在此之后每次调用 yes() 确实不需要存储在变量中。
  • 第一个引用bool yes(char c); 不是调用——它是函数的原型声明(在这种情况下是多余的)。由于这种混乱,我建议 OP 将其删除。
猜你喜欢
  • 1970-01-01
  • 2023-04-11
  • 2019-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-06
相关资源
最近更新 更多