如何有条件地实例化不同的子类
How to instantiate different child classes conditionally?
例如,在主函数中,我想要获得用户的输入。根据输入,我将创建Rectangle
或Circle
,它们是Object
的子类。如果没有输入(或未知),那么我将只创建一个通用对象。
class Object
{
public:
Object();
void Draw();
private:
....
};
class Rectangle:public Object
{
public:
Rectangle();
.... //it might have some additional functions
private:
....
};
class Circle:public Object
{
public:
Circle();
.... //it might have some additional functions
private:
....
};
主要功能:
string objType;
getline(cin, objType);
if (!objType.compare("Rectangle"))
Rectangle obj;
else if (!objType.compare("Circle"))
Circle obj;
else
Object obj;
obj.Draw();
当然,上面的代码不起作用,因为我无法在If语句中实例化对象。所以我尝试了这样的东西。
Object obj;
if (!objType.compare("Rectangle"))
obj = Rectangle();
else if (!objType.compare("Circle"))
obj = Circle();
obj.Draw();
这段代码可以编译,但它不能完成我想要的任务。出于某种原因,对象没有按照子类应该的方式启动(例如,我在子类中以不同的方式设置了一些对象的成员变量,特别是向量)。然而,当我在Child类构造函数处设置断点时,它确实贯穿其中。
那么,在一些if语句中,我应该如何将实例化对象作为它的子类呢??
您可以在if
语句中创建自动对象,但它们将在创建范围结束时被销毁,因此无法解决此问题。
你不能做obj = Rectangle()
的原因是因为切片。
你必须有一个指向Object
的指针。指向基础对象的指针也可以指向子对象的实例。然后,您可以使用new
在if
内动态创建对象(使用new
创建的对象忽略作用域,只有当您在指向它们的指针上调用delete
时才会被销毁),然后在完成后使用delete
:
Object* obj = NULL; // obj doesn't point to anything yet
string objType;
getline(cin, objType);
if (objType == "Rectangle")
obj = new Rectangle; // make obj point to a dynamic Rectangle
else if (objType == "Circle")
obj = new Circle; // make obj point to a dynamic Circle
else
obj = new Object; // make obj point to a dynamic Object
obj->Draw(); // draw whatever shape obj really points to
delete obj; // deallocate dynamic object
或者,您可以使用智能指针,然后不必担心手动释放对象:
std::unique_ptr<Object> obj(NULL); // obj doesn't point to anything yet
string objType;
getline(cin, objType);
if (objType == "Rectangle")
obj.reset(new Rectangle); // make obj point to a dynamic Rectangle
else if (objType == "Circle")
obj.reset(new Circle); // make obj point to a dynamic Circle
else
obj.reset(new Object); // make obj point to a dynamic Object
obj->Draw(); // draw whatever shape obj really points to
// the unique_ptr takes care of delete'ing the object for us
// when it goes out of scope
相关文章:
- 设计一个只能由特定类实例化的类(如果可能的话,通过make_unique)
- C++包括类名间距和类实例化
- 如何使用其中一个具体类实例化抽象类?
- 不带尖括号的模板类实例化
- 返回具体子类实例的 C++ 虚拟类函数
- 使用父类实例化的向下转换对象
- 模板类实例化中的指针转换无效
- 将子类实例保存在父类型变量中并通过父变量使用 Child 函数?
- 类的私有成员在我的类实例化期间更改,即使他们不应该
- 反向函数不反转类实例化的引用字符串
- 在类实例化时生成一个数字
- 谷歌测试 - 为模板类实例化生成值
- 使用派生类实例化基类,而不在对象定义中使用指针
- 模板类实例化如何与类继承协同工作
- 枚举器而不是用于类实例化的构造函数
- 使用std :: make_shared抽象类实例化的错误
- 通过纯虚拟函数防止类实例化
- C 11枚举类实例化
- 阿达水果示例中的 Bizare 类实例化
- 从标头中的类实例化对象