C++指针与整数比较编译错误

C++ pointer compared with integer compile error

本文关键字:编译 错误 比较 整数 指针 C++      更新时间:2023-10-16

我的教授要求我们在编写代码时使用c++中的while函数。我不断返回相同的错误,所以我写了一个简单的代码来理解while循环。还是卡在这个部位。这显然不是我程序的结束,我只是被while函数卡住了。有什么想法吗?

#include <iostream>
#include <cstdlib>
using namespace std;
void response (){
    cout<<" Continue loop function?n";
    cout <<"y - yesnn - non";
    char response='y';
    cin>> response;
    return;
}
int main (){
    response ();
    while (response=='y')
    return 0;
}

您无法访问main()中的函数本地response变量。

在这一行

 while (response=='y')

response被解释为response()函数的地址,而'y'会导致您看到的错误。


正如其他人提到的,你应该有这样的

char response (){
    cout<<" Continue loop function?n";
    cout <<"y - yesnn - non";
    char resp='y';
    cin >> resp;
    return resp;
}
int main (){
    while (response()=='y'); // << also note the semicolon here
    return 0;
}

这里有几个错误。你的主要功能应该是这样的:

int main()
{
    while (response() == 'y')
    { //must have either an empty body or a semicolon here, 
      //otherwise our return statement will become the loop body!
    }
    return 0;
}

此外,response()函数应该返回局部变量response,以便将其值返回给main。由于作用域的原因,不能在响应函数之外使用response变量。

您的(错误的)主函数当前所做的是调用response()函数,然后尝试将响应函数与字符文字'y'进行比较。然而,这并不是比较刚从函数返回的值,而是比较函数本身的内存地址(指针)。

C++允许您拥有相同的变量和函数,但这通常是个坏主意。您可能希望为response()函数或response局部变量指定不同的名称。

正在等待布尔值。为了将"y"与响应进行比较,必须将返回类型从void更改为char:

char response (){
    cout<<" Continue loop function?n";
    cout <<"y - yesnn - non";
    char response='y';
    cin>> response;
    return response;
}