C++指针与整数比较编译错误
C++ pointer compared with integer compile error
我的教授要求我们在编写代码时使用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;
}
相关文章:
- std::is_base_of表示ctor编译错误
- Qt5:使用QCommandLineParser类时出现奇怪的编译错误
- 如何修复sfml c++代码编译错误
- 使用 MATLAB 编码器生成C++代码:编译错误"undefined reference to `rgb2gray_tbb_real64'"
- 使用外部SDK工具链文件在VisualStudio上生成项目编译错误
- vscode下的Arduino代码出现意外编译错误
- 第三方 API 中的编译错误 - Visual Studio
- std::cout输出int时出现编译错误
- 奇怪的代码抛出编译错误模板< J,int aSize=10> C2143:语法错误:在"<"之前缺少";"
- 提升图广度优先搜索前置编译错误
- C++ 中的编译错误:未定义对"主"的引用 collect2:错误:ld 返回 1 个退出状态
- 使用带有 ref 参数的成员函数创建线程时出现编译错误
- 我在C++中遇到了这个奇怪的编译错误
- 在C++中使用 Catch 测试框架编译错误"error: expected ';' at end of declaration list"
- 使用 std::enable_if 限制派生类的模板参数时出现编译错误
- 现代OpenGL和GLEW Libraray的编译错误
- C++ 编译错误:意外的类型名称"字符串":预期的表达式
- C ++程序编译错误,找不到/访问文件
- 使用直接大括号初始化时,C++ 编译错误"声明末尾的预期";"
- 为什么传递非静态成员函数会导致编译错误?