Domanda

I'm trying to build a heterogeneous list that allocates memory to the heterogeneous array dynamically. I'm having some trouble with the declarations necessary to make this work. So far I have something like:

class Class1
{
 public:
 Class1 * GetList( int i, Class1& c );
 void Create( int size );

 private:
 Class1 ** list1;
};

class Class2: public Class1
{
  ...
};

Class1 * GetList( int i, Class1& c )
{
  return c.list1[i];
}

void Class1::Create( int size )
{
 list1 = new Class1*[size];
}

int main()
{ 
 Class1 c;
 int size = 0;

 cin >> size;

 c.Create( size );

 for( int i = 0; i < size; i ++ )
 {
    c.GetList( i, c ) = new Class2;

    c.GetList( i, c )->SetParams( some params );  
 }

}

I'm wondering if I'm using the heterogeneous list to store pointers of the parent class dynamically and call them in main correctly. Any help would be much appreciated.

È stato utile?

Soluzione

According to your usage and following what we've said in the comments, you should change GetList for this:

Class1 *& GetList( int i )
{
 return list1[i];
}

Mind the &. Otherwise your assignment using GetList(i) =... will be useless.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top