例如,在main函数中,我想获取用户的输入。根据输入,我将创建一个Rectangle
or a 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 语句中将实例化对象作为其子类?
You can创建自动对象if
语句,但它们将在创建它们的作用域结束时被销毁,因此它们无法解决此问题。
你不能这样做的原因obj = Rectangle()
其一是因为slicing https://stackoverflow.com/questions/274626/what-is-the-slicing-problem-in-c.
你必须有一个指向Object
。指向基对象的指针也可以指向子对象的实例。然后就可以在里面动态创建对象了if
with new
(使用创建的对象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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)