C++无效功能行使错误
C++ void function exercise error
我是C++新手,目前正在学习空函数。我正在尝试使用 void 函数编写一个对数字进行平方的函数。这是我的代码。
#include "std_lib_facilities.h"
void square(int);
int main()
{
int x = 0;
cout << "Please enter a number. It will be squared.";
cin >> x;
cout << x << 't' << square(x);
}
void square(int x)
{
int y = x*x;
cout << y;
}
IDE 给我的错误是:
no match for 'operator<<' (operand types that are 'std::basic_ostream<char>'
and 'void')
根据经验,很多人会问头文件std_lib_facilities.h
,这不是问题。我可以这么说,因为我使用这个头文件做了很多练习,它们都有效。
提前感谢您的帮助!
void 函数不能直接返回值。 大多数人会使用非 void 函数来实现平方,如下所示:
int square(int x)
{
return x * x;
}
我看到您的 square
函数将平方值写入std::cout
本身。 这很奇怪,但如果你真的想这样做,你应该将main
函数的最后一行替换为:
cout << x << 't';
square(x);
通常不能在表达式中使用 void 函数的结果,这是原始代码的问题。
square()
是无效的 - 即它不返回任何内容。
cout << x << 't' << square(x);
尝试打印 square()
的返回值(我们已经说过它不存在(。这毫无意义,所以编译器抱怨。
您要做的是使square
返回一个 int 而不是打印它。
int square(int x)
{
return x*x;
}
我想
更改返回类型会使错误消失。编译器错误是因为没有重载版本的<<将void作为参数,因为您的函数(错误地(告诉编译器。
相关文章:
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 在气泡排序程序中未声明错误功能
- 错误:(-210:不支持的格式或格式组合)功能'create'中的硬件视频解码器不支持视频源
- 为什么每当我尝试运行此链接列表删除功能时都会收到分段错误错误?
- C++中"覆盖功能的异常规范比基本版本更宽松"的奇怪错误
- 错误:在尝试检测 std::cout 是否<< t 时,功能强制转换为数组类型;有效
- 访问我以前可以访问的功能时出现分段错误
- 分割错误:向量中的擦除功能
- 如何组织 git 工作流以修复错误并同时引入新功能
- 错误:当我尝试使用引用时,使用已删除的功能
- 错误:调用'strcmp'没有匹配函数(尝试设置显示用户信息功能)
- 这种错误的原因是什么:将"功能"重新定义为不同类型的符号
- Boost进程"系统"功能中的错误处理
- 为什么我的删除功能总是出现分段错误
- 想要构建一些必要的库来检测功能.出现一些错误
- C++ 添加编译器警告,以错误使用自定义打印/日志功能
- Visual C:命名空间范围错误或晦涩功能?
- C++插入排序错误功能不起作用
- 错误功能出现问题
- 使用VideoWriter_GPU时如何解决OpenCV错误"功能未实现(当前构建或平台禁用了称为功能)?