Why can I define structures and classes within a function in C++?

后端 未结 6 1586
日久生厌
日久生厌 2020-12-04 07:03

I just mistakenly did something like this in C++, and it works. Why can I do this?

int main(int argc, char** argv) {
    struct MyStruct
    {
      int some         


        
6条回答
  •  南方客
    南方客 (楼主)
    2020-12-04 07:56

    One application of locally-defined C++ classes is in Factory design pattern:

    
    // In some header
    class Base
    {
    public:
        virtual ~Base() {}
        virtual void DoStuff() = 0;
    };
    
    Base* CreateBase( const Param& );
    
    // in some .cpp file
    Base* CreateBase( const Params& p )
    {
        struct Impl: Base
        {
            virtual void DoStuff() { ... }
        };
    
        ...
        return new Impl;
    }
    
    

    Though you can do the same with anonymous namespace.

提交回复
热议问题