基于函数参数创建对象 C++
假设我有一个成员函数,它创建一个新对象并将其放入类中的数据结构(在本例中为映射):
Class A
{
std::map<std::pair<int,int>, BaseClass*> store;
//...
public:
void createObject(?a?)
{
BaseClass* temp = new ?a?;
//place in map...
};
};
其中 ?a?
是一个可用于创建一个参数的参数对象可以是从 BaseClass
派生的许多不同类。我能想到的唯一方法是将 ?a?
设为 int
,然后手动将每种类型键入 switch 语句。
Say I have a member function that creates a new object and places it into a data structure (in this case a map) in the class:
Class A
{
std::map<std::pair<int,int>, BaseClass*> store;
//...
public:
void createObject(?a?)
{
BaseClass* temp = new ?a?;
//place in map...
};
};
Where ?a?
is an argument that can be used to create an object that can be a number of different classes derived from BaseClass
. The only way I can think of doing this is by making ?a?
an int
, and manually typing each type into a switch statement.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用成员函数模板。在您的示例上下文中:
调用方式:
其中
a
是A
的实例,B
是从BaseClass 派生的类型
。Use a member function template. In the context of your example:
Invoke with:
Where
a
is an instance ofA
, andB
is a type derived fromBaseClass
.模板是比枚举更好的解决方案,因为它不需要任何维护。任何新的子类都将自动受到支持。指针类型之间的类型安全保证 T 是 temp 的子类(否则赋值将失败)。
如果没有依赖参数,编译器无法自动推导模板类型,因此您需要对其进行限定。
A template is a better solution than an enum because it doesn't require any maintenance. Any new subclasses will automatically be supported. Type safety between pointer types guarantees that T is a subclass of temp (otherwise the assignment will fail).
The compiler cannot deduce the template type automagically without a dependant argument, so you'll need to qualify it.
取决于您如何知道要创建什么样的对象。
如果基于 int 是合理的(例如某个函数的返回码),那么 switch 语句就可以了。请注意,您需要通过调用 new 来创建每个对象的类型,然后将对象指针转换为 BaseClass 以放入映射中。
如果您要传递该类型的对象,请使用模板。编辑:作为乔恩的回答
Depends how you know what kind of object to create.
If it is reasonable to base that on an int (eg a return code from some function) then a switch statement is fine. Note that you need to create each object with a call to new for it's type and then cast the object pointer to BaseClass to put into the map.
If you are passing in an object of the type then use a template. edit: as Jon's answer
您应该枚举可以创建的可能类,并将其传递给 createObject 函数,例如:
这样,您实际上将整数作为参数传递,但您的代码更易于理解、可修改和可维护。
You should make an enumeration of the possible classes that can be created and pass one to createObject function, for example:
This way, you are actually passing an integer as a parameter, but your code is more understandable, modifiable and maintainable.