我们可以在C ++函数内部包含函数吗? [英] Can we have functions inside functions in C++?

查看:109
本文介绍了我们可以在C ++函数内部包含函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的意思是:

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

  return 0;
}


推荐答案

现代C ++-可以使用lambdas !



在当前版本的c ++(C ++ 11,C ++ 14和C ++ 17)中,您可以在函数内部使用a形式的函数lambda:

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!"); 
    }
}

Lambda也可以通过** capture-引用*。通过按引用捕获,lambda可以访问在lambda范围内声明的所有局部变量。它可以正常地修改和更改它们。

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和C ++ 03-不直接,但是可以,在本地类内部具有静态函数



C ++不直接支持该功能。

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

C++ doesn't support that directly.

也就是说,您可以拥有本地类,并且可以具有函数(非静态 static ),因此您可以对此进行扩展,尽管有点麻烦:

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;
}

但是,我会质疑这种做法。每个人都知道(好吧,无论如何:))C ++不支持本地函数,因此它们习惯于不使用它们。但是,它们并不适用于这种冲突。我会花一些时间在这段代码上,以确保它只存在于本地函数中。不好。

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.

这篇关于我们可以在C ++函数内部包含函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆