gpt4 book ai didi

c++ - C++ 中奇怪的函数声明和 lambdas

转载 作者:行者123 更新时间:2023-12-01 14:15:03 24 4
gpt4 key购买 nike

所以我正在阅读一些笔记,但我对一些奇怪的声明感到困惑。
在下面的代码段中,您可以看到下面的代码块有一个分配给 auto 变量的函数

#include<iostream>
using namespace std;
void Hi(int a)
{
cout << "Hi" << a << endl;
}

int main()
{
auto Print = Hi;
Print(5);
}

但是函数(此处为'Hi')没有方括号 () 并且它仍然有效..那么它是如何工作的呢?
让我更感兴趣的是它的类型是什么?最后,当我们调用该变量时,它会打印“Hi5”。

我对这部分很好奇,因为这只是我们代码的一个示例部分。
我们需要制作一个 for-each 循环函数的工作示例,以使用这种类型在 vector 中显示值。

我似乎无法找到任何线索,因为我什至不知道类型……但是我们的教授确实提到使用“lambdas”更好,我在网上查了一下,但我无法清楚地了解它是什么.任何提醒都会非常有帮助。

最佳答案

But the function ('Hi' here) doesnt have brackets () and it still works..so how does it work?



你在这里观察到的是一个 函数指针 ,顾名思义,通常是指向函数的指针。
毕竟,函数只是 CPU 指令,存储在二进制可执行文件的某个位置,该函数指针指向内存中函数的地址。
我们实际上是在检索那些 CPU 指令的位置,其中使用了引用( & ),这最终等同于 &Hi . (有一个隐式转换,因此写 Hi 就足够了)

What ticks me more is what is its type?



void(*Print)(int) type,一个空类型的函数指针,接受一个整数作为参数。第一个 ()取消引用 *包含函数的名称,即 Print在你的例子中。
(它可以是任何东西,取决于您的自动变量的名称)第二个 ()表示传递给函数的参数的类型,在你的例子中是一个整数,所以有一个 int .
由于它是一个有效类型,您也可以使用 typedef 来定义它:

typedef void(*printHiFunction)(int);

printHiFunction Print = Hi;
Print(5);

We needed to make a working example of a for-each loop function to display values in a vector using such a type. I cant seem to find any lead on it as I dont even know the type..but our professor did mention to use 'lambdas' for the better, which I looked up in the net but I couldnt get a clear idea of what it is. Any heads up would be really helpful.



我不明白您如何仅使用函数指针来实现它(或者如果没有它,您有什么用处)。
否则,您的教授可能希望您绝对使用 lambda。
它只是一个匿名临时函数,可以在必要时调用(并相应地像扔掉的函数一样丢弃),也可以作为参数传递给函数。
如需更多信息,您可以引用 here .

对于基于范围的循环,您至少需要传入一个 vector ,您可以将其声明为 const并像左值一样通过引用传递它,并将函数指针作为第二个参数传递给您的每个循环函数。
然后,您可以使用 lambda 代替带有 int 的函数指针。当您在 main() 中调用该整数时只打印该整数的参数:

void ForEach(const std::vector<int>& values, void(*functionPointer)(int))
{
for (int value : values)
functionPointer(value);
}
int main()
{
std::vector<int> values = {1, 2, 3, 4, 5};
ForEach(values, [](int value)
{ std::cout << value << " "; });
}

输出: 1 2 3 4 5

关于c++ - C++ 中奇怪的函数声明和 lambdas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61211707/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com