c++ - 如何有条件地实例化不同的子类?

标签 c++ class inheritance

比如在main函数中,我想获取用户的输入。根据输入,我将创建一个 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();

此代码可以编译,但它不会执行我想要的操作。由于某种原因,该对象没有按照子类应有的方式启动(例如,我在子类中设置了一些对象的成员变量,具体来说,一个 vector ,不同)。但是,当我在 Child 类构造函数中放置一个断点时,它确实运行到那里。

那么我应该如何在某些 if 语句中将实例化对象作为其子类?

最佳答案

可以if 语句中创建自动对象,但它们将在创建它们的范围结束时被销毁,因此它们不适用于此问题.

你不能执行 obj = Rectangle() 的原因是因为 slicing .

您必须有一个指向对象 的指针。指向基础对象的指针也可以指向子对象的实例。然后,您可以使用 newif 中动态创建对象(使用 new 创建的对象无视作用域,仅在您调用 时销毁删除指向它们的指针上的),然后在完成后删除它:

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

关于c++ - 如何有条件地实例化不同的子类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9459270/

相关文章:

c++ - 无法打开包含文件错误但能够找到文件

c# - 分类库

c++ - 你如何初始化私有(private)成员函数指针的静态映射?

vb.net - 在 VB 中,如何强制继承类使用类的属性?

java - 继承 - 在子类中使用 super.equals() 覆盖父类(super class) equals 中使用的方法

c# - 通过测验了解 C# 中的嵌套泛型类

C++如何将类数组视为主要类型数组?

c++ - 查询集成 Fortran 和 C++ 代码

php - 计算输出不理想

python - 如何在 tkinter 中单击按钮后更新 Canvas 上的文本