Why can't I define a function inside another function?

后端 未结 11 1897
陌清茗
陌清茗 2020-11-27 16:55

This is not a lambda function question, I know that I can assign a lambda to a variable.

What\'s the point of allowing us to declare, but not define a function insid

11条回答
  •  星月不相逢
    2020-11-27 17:33

    The first one is a function definition, and it is not allowed. Obvious, wt is the usage of putting a definition of a function inside another function.

    But the other twos are just declarations. Imagine you need to use int two(int bar); function inside the main method. But it is defined below the main() function, so that function declaration inside the function makes you to use that function with declarations.

    The same applies to the third. Class declarations inside the function allows you to use a class inside the function without providing an appropriate header or reference.

    int main()
    {
        // This is legal, but why would I want this?
        int two(int bar);
    
        //Call two
        int x = two(7);
    
        class three {
            int m_iBar;
            public:
                three(int bar):m_iBar(13 + bar) {}
                operator int() {return m_iBar;}
        };
    
        //Use class
        three *threeObj = new three();
    
        return 0;
    }
    

提交回复
热议问题