|
|
Am 14.05.2011 18:43, schrieb Darren New:
> Is it possible to put a class into a variable in C++?
>
> In particular, assume I have a superclass "Thing", with subclasses
> Alpha, Beta, Gamma. I want to instantiate one of each of the subclasses
> and put each instance into a vector.
>
> Thing* thing;
> thing = new Alpha(1,true);
> stuff.push_back(thing);
> thing = new Beta(1,true);
> stuff.push_back(thing);
> thing = new Gamma(1,true);
> stuff.push_back(thing);
>
> Is there any way to do that with only one call to new?
>
> In something like Tcl or Python, I'd do something like
>
> for x in [Alpha, Beta, Gamma] {
> thing = new x(1,true);
> stuff.push_back(thing);
> }
>
> Is there any way to do anything similar in C++?
Not out of the box; you could use a factory-based approach though, e.g.:
class Thing_Factory_Base {
public:
virtual Thing* New(int i, bool b) = 0;
}
template<class T>
class Thing_Factory : public Thing_Factory_Base {
public:
virtual Thing* New(int i, bool b)
{ return new T(i,b); }
}
Thing_Factory<Alpha> Alpha_Factory = new Thing_Factory<Alpha>();
Thing_Factory<Beta> Beta_Factory = new Thing_Factory<Beta>();
Thing_Factory<Gamma> Gamma_Factory = new Thing_Factory<Gamma>();
list = Factory_List[3] {
Alpha_Factory,
Beta_Factory,
Gamma_Factory
};
for (int i = 0; i < 3; i ++)
stuff.push_back(Factory_List[i].New(1,true));
Post a reply to this message
|
|