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

后端 未结 6 1594
日久生厌
日久生厌 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:53

    It's for making arrays of objects that are properly initialized.

    I have a class C which has no default constructor. I want an array of objects of class C. I figure out how I want those objects initialized, then derive a class D from C with a static method which provides the argument for the C in D's default constructor:

    #include 
    using namespace std;
    
    class C {
    public:
      C(int x) : mData(x)  {}
      int method() { return mData; }
      // ...
    private:
      int mData;
    };
    
    void f() {
    
      // Here I am in f.  I need an array of 50 C objects starting with C(22)
    
      class D : public C {
      public:
        D() : C(D::clicker()) {}
      private:
        // I want my C objects to be initialized with consecutive
        // integers, starting at 22.
        static int clicker() { 
          static int current = 22;
          return current++;
        } 
      };
    
      D array[50] ;
    
      // Now I will display the object in position 11 to verify it got initialized
      // with the right value.  
    
      cout << "This should be 33: --> " << array[11].method() << endl;
    
      cout << "sizodf(C): " << sizeof(C) << endl;
      cout << "sizeof(D): " << sizeof(D) << endl;
    
      return;
    
    }
    
    int main(int, char **) {
      f();
      return 0;
    }
    

    For the sake of simplicity, this example uses a trivial non-default constructor and a case where the values are known at compile time. It is straightforward to extend this technique to cases where you want an array of objects initialized with values that are known only at runtime.

提交回复
热议问题