开发者

Generating Instances of Different Inherited Classes through Shared Pointers

I'm a novice in C++ so please excuse the primitve coding technique.I'm trying to figure out how to create a function that generate shared pointers to different inherited classes.

class base{
/*.... members ...*/};

class derived1: public base{
/*.... members ...*/

derived1(int){};

~derived1(){};

}

class derived2: public base{
/*.... members ...*/

derived2(int,int){};

~derived2(){};

}

In order to create multiple instances of each derived strategy, i have two different functions that do that manually through shared pointers.

typedef std::tr1::shared_ptr<Base> Base_ptr_type;

void fn1(int i){
for (t=0;t<=no_instances1;t++)

    Base_ptr_type  p1(new derived1(i));
}

void fn2(int i, int j){
for (t=0;t<=no_instances2;t++)

    Base_ptr_type  p2(new derived1(i,j));
}

I would like to combine those two different functions.in the future, i will be developing more derived classes and i'm looking for a function that yould take the derived class constructor parameters as its arguments.Somthing along

Base_ptr_type p1(new derived1(i));

Base_ptr_type p2(new derived2(i,i);


void Global_fn(int no_instances, Base_ptr_type ptr ){ ??????  }

so that when we apply Global_fn(p1), it generates a number of instances of derived1 and Global_fn(p2), it generates a number of instances of derived2 based on the constructor parameter of each respective derived class.

Thank you for all your help in advance

Thank you Igor. your solution gives me a linking problem error LNK2001: unresolved external symbol! I'm suspecting that your vitualfunction in the base and derived classes is not a void function and must return somthing? I dont see a declaration of the typedef std::tr1::shared_ptr<Base> Base_ptr_type pointers below to your开发者_C百科 code, which are necessary to create the instances with the required parameters?

    Base_ptr_type p1(new derived1(i));

    Base_ptr_type p2(new derived2(i,i);

Thanks again,

cheers


You should use a factory, independent or as a part of base, derived1, and derived2.


One of the ways to do it: add overloaded create_instance function to all classes:

class base{
public: 
 virtual base* create_instance() = 0;
};

class derived1: public derived1{
public: 
 virtual base* create_instance(); // creates derived1
};

class derived2: public base{
public: 
 virtual base* create_instance(); // creates derived2
};

void Global_fn(int no_instances, Base_ptr_type ptr )
{ 
   for (int i = 0; i < no_instances; i++)
     ptr->create_instance(); 
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜