我们可以在函数内部有函数吗?(Can we have functions inside functions in C++?)

系统教程 行业动态 更新时间:2024-06-14 16:57:40
我们可以在函数内部有函数吗?(Can we have functions inside functions in C++?)

我的意思是:

int main() { void a() { // code } a(); }

I mean something like:

int main() { void a() { // code } a(); return 0; }

最满意答案

不,C ++不支持。

编辑:这个答案是老的。 同时,C ++ 11还可以实现类似的结果 - 看下面的答案。

也就是说,您可以拥有本地课程,并且可以具有(非static或static )功能,因此您可以在某种程度上得到这一点,尽管它有点像一个kludge:

int main() // it's int, dammit! { struct X { // struct's as good as class static void a() { } }; X::a(); return 0; }

但是,我会质疑这个实践。 每个人都知道(嗯,现在你做,无论如何:) )C ++不支持本地功能,所以他们习惯于没有它们。 然而,它们不被用于该污泥。 我会在这段代码上花费一段时间来确保它只是在那里允许本地的功能。 不好。

Modern C++ - Yes with lambdas!

In current versions of c++ (C++11, C++14, and C++17), you can have functions inside functions in the form of a lambda:

int main() { // This declares a lambda, which can be called just like a function auto print_message = [](std::string message) { std::cout << message << "\n"; }; // Prints "Hello!" 10 times for(int i = 0; i < 10; i++) { print_message("Hello!"); } }

Lambdas can also modify local variables through **capture-by-reference*. With capture-by-reference, the lambda has access to all local variables declared in the lambda's scope. It can modify and change them normally.

int main() { int i = 0; // Captures i by reference; increments it by one auto addOne = [&] () { i++; }; while(i < 10) { addOne(); //Add 1 to i std::cout << i << "\n"; } }

C++98 and C++03 - Not directly, but yes with static functions inside local classes

C++ doesn't support that directly.

That said, you can have local classes, and they can have functions (non-static or static), so you can get this to some extend, albeit it's a bit of a kludge:

int main() // it's int, dammit! { struct X { // struct's as good as class static void a() { } }; X::a(); return 0; }

However, I'd question the praxis. Everyone knows (well, now that you do, anyway :)) C++ doesn't support local functions, so they are used to not having them. They are not used, however, to that kludge. I would spend quite a while on this code to make sure it's really only there to allow local functions. Not good.

更多推荐

本文发布于:2023-04-13 12:21:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/8cbca446aaeaa1a3afaaf9f47a60530f.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   我们可以   functions

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!