C++无效功能行使错误

C++ void function exercise error

本文关键字:错误 功能 无效 C++      更新时间:2023-10-16

我是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作为参数,因为您的函数(错误地(告诉编译器。