开发者

In C++, can I represent a class type as a variable?

I would like to call a static method from a class that I'll determine at run-time, but which I know subclasses a given class. So let's say I have these classes

class super {
    public:
    super();
    static super *loadMe (ifstream &is);
}

class subA : public super {
   public:
   subA();
   static super *loadMe (ifstream &is);
}

class subB : public super {
   public:
   static super *loadMe (ifstream &is);
   private:
   subB();
}

And let's say I want to determine at run-time (based on what's in the file) whether to load a subA or subB next. One way I could do this would be to use an empty object to invoke the method

super getLoadType (ifstream &is) { if(complicatedFunctionOfIs(is)) return subA(); return subB()}

super *newObj = getLoadType(is).loadMe(开发者_开发知识库is);

but I've made the no-argument constructor of subB private, so I can't do that here. But I don't actually need a super object, just the class type of a super subclass. So is there a way to represent that as a variable?

EDIT: I'm aware that in this case, I could return a function pointer, but I'm considering more complex examples that might involve needing to call more than one static function.


You might want to look at the Factory Pattern. If you are designing a plugin architecture you can simple have a function that returns a pointer to the desired factory. Polymorphism can then do the rest for you.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜