类实例化 [英] class instantiation
问题描述
大家好,
我有一个类,例如GeneralBuilding
,它可以是SmallBuilding
,MediumBuilding
,LargeBuilding
等类之一,具体取决于传递给Building构造函数的参数. SmallBuilding
,MediumBuilding
和LargeBuilding
具有共同的基类Building.
I have a class, say GeneralBuilding
, which could be one of the classes SmallBuilding
, MediumBuilding
, LargeBuilding
, etc...., depending on the parameters passed to the Building constructor. SmallBuilding
, MediumBuilding
, and LargeBuilding
have a common base class Building.
执行时是否有可能
GeneralBuilding x(1) // 1 bedroom...
x是由构造函数根据构造函数参数选择的形式(即,出于参数的考虑,如果no.bedrooms = 1,则x
将是类类型SmallBuilding
,如果bedrooms = 2,则x
>的类型为MediumBuilding
,如果卧室> = 3,则d的类型为LargeBuilding
)?
that x is of a form chosen by the constructor depending on the constructor parameters (i.e. for sake of argument if no. bedrooms = 1 then x
would be of class type SmallBuilding
, if bedrooms = 2 then x
would of type MediumBuilding
, and if bedrooms >= 3 then d would be of type LargeBuilding
) ?
我对此感兴趣的原因是,我需要根据建筑物的大小来更改每种GeneralBuilding
类型的功能,并且我试图避免在一个内部包含一堆"if then
"语句班级.我想分散责任,使课堂变得整洁,整洁,安全,可维护等.
The reason I''m interested in this is that I need the functionality for each type of GeneralBuilding
to change depending on the building size, and I am trying to avoid a bunch of "if then
" statements within one class. I''d like to spread the responsibilty to make the classes clean, tidy, safer, more maintainable etc.
我现在正在调查...
I''m looking into it now...
Paul
推荐答案
不,您不能以这种方式选择类的类型.但是,通过使用指针(或引用),您可以通过操纵指向基类的指针来以相同的方式操作所有建筑物(这称为多态,如果您需要更多信息,可以使用google).
所需的内容是虚拟构造函数,但是C ++中没有此类机制.这是为什么在C ++中没有这样的东西的简短版本: http://www.research.att.com/~bs/bs_faq2.html#virtual-ctor
您可以将类的实例委托给外部类(工厂类),这将使请注意根据参数创建正确的类型,并将返回指向基类的指针.总体上就是这样.
No, you can''t select the type of the class this way. However, by using pointers (or references), you can manipulate all buildings the same way by manipulating pointers to the base class (this is called polymorphism, google for it if you want more information).
What you want are virtual constructors, but such mechanisms are not available in C++. Here''s the short version of why there are no such things in C++: http://www.research.att.com/~bs/bs_faq2.html#virtual-ctor
What you could is delegate the instanciation of the class to an external class (a factory class), which will take care of creating the correct type depending of the parameter and will return a pointer to the base class. That''s how it is done in general.
这篇关于类实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!