Set array of object to null in C++

前端 未结 4 1342
深忆病人
深忆病人 2021-02-06 04:46

Suppose I have an array of objects of type Foo in C++:

Foo array[10];

In Java, I can set an object in this array to null simply by:

<         


        
4条回答
  •  抹茶落季
    2021-02-06 05:16

    Other way that you have is using one dynamic array of pointers of Foo like this:

    Foo** array = new Foo*[10];// Pointer of array of pointers.
    

    Then you can initialize all this pointers to objects Foo

    for(int i=0;i<10;i++)
        array[i] = new Foo();// Give memory to pointers of object Foo in array
    

    assign null to one item of array:

    array[0] = 0;
    

    I think that in C++, NULL is 0. This means it can even be assigned to an int or anywhere a 0 is acceptable. Conventionally, it's only used with pointers.

    For delete this memory:

    for(int i=0;i<10;i++)
        delete array[i];
    

    and finally

    delete[] array;
    

    Code Example:

    #include 
    #include 
    class Foo
    {
      private:
        int a;
      public:
        Foo()
        {
          a = 0;
        }
       void Set_V(int p){a = p;}
       int Get_V(){return a;}
    };
    
    int main()
    {
      Foo **array = new Foo*[10];
      for(int i=0;i<10;i++)
       {
         array[i] = new Foo();
       }
    
      //array[0] = 0;
      for(int i=0;i<10;i++)
        array[i]->Set_V(i);
      for(int i=0;i<10;i++)
        cout<Get_V()<

提交回复
热议问题