2012-02-27 59 views
6

例如,在主函数中,我想获取用户的输入。根据输入,我将创建一个RectangleCircle,它们是子类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(); 

当然,上面的代码将无法工作,因为我不能实例如果语句中的对象。所以我尝试了这样的事情。

Object obj; 
if (!objType.compare("Rectangle")) 
    obj = Rectangle(); 
else if (!objType.compare("Circle")) 
    obj = Circle(); 


obj.Draw(); 

这段代码会编译,但它不会做我想要的。出于某种原因,该对象不是按照子类的方式启动的(例如,我在子类中设置了某些对象的成员变量,特别是矢量)。但是,当我在Child类构造函数中放置一个断点时,它确实在那里运行。

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

回答

10

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

你不能这样做obj = Rectangle()的原因是因为slicing

你必须有一个指向Object的指针。指向基础对象的指针也可以指向子对象的实例。然后,您可以动态创建ifnew内的对象(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 
+0

它的工作原理! 除了我的问题的解决方案,感谢您提供良好的解释如何类和指针工作在C + +! – tuzzer 2012-02-27 02:36:46

相关问题