is it possible in C or C++ to create a function inside another?

后端 未结 15 2018
迷失自我
迷失自我 2020-12-15 09:18

Could someone please tell me if this is possible in C or C++?

void fun_a();
//int fun_b();
...
main(){
   ...
   fun_a();
   ...
   int fun_b(){
     ...
            


        
15条回答
  •  清歌不尽
    2020-12-15 09:54

    You can nest a local class within a function, in which case the class will only be accessible to that function. You could then write your nested function as a member of the local class:

    #include 
    
    int f()
    {
        class G
        {
        public:
            int operator()()
            {
                return 1;
            }
        } g;
    
        return g();
    }
    
    int main()
    {
        std::cout << f() << std::endl;
    }
    

    Keep in mind, though, that you can't pass a function defined in a local class to an STL algorithm, such as sort().

    int f()
    {
        class G
        {
        public:
            bool operator()(int i, int j)
            {
                return false;
            }
        } g;
    
        std::vector v;
    
        std::sort(v.begin(), v.end(), g);  //  Fails to compile
    }
    

    The error that you would get from gcc is "test.cpp:18: error: no matching function for call to `sort(__gnu_cxx::__normal_iterator > >, __gnu_cxx::__normal_iterator > >, f()::G&)' "

提交回复
热议问题