在 C++ 中,我可以将类类型表示为变量吗?
我想从我将在运行时确定的类中调用静态方法,但我知道它是给定类的子类。假设我有这些类
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();
}
,假设我想在运行时(根据文件中的内容)确定接下来是否加载 subA 或 subB。我可以做到这一点的一种方法是使用一个空对象来调用该方法
super getLoadType (ifstream &is) { if(complicatedFunctionOfIs(is)) return subA(); return subB()}
super *newObj = getLoadType(is).loadMe(is);
,但我已将 subB 的无参数构造函数设为私有,所以我不能在这里这样做。但我实际上并不需要超级对象,只需要超级子类的类类型。那么有没有办法将其表示为变量呢?
编辑:我知道在这种情况下,我可以返回一个函数指针,但我正在考虑更复杂的示例,可能需要调用多个静态函数。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能想查看工厂模式。如果您正在设计一个插件架构,您可以简单地拥有一个返回指向所需工厂的指针的函数。多态性可以为您完成剩下的工作。
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.