创建类对象的指针数组 [英] Creating array of pointers to class object

查看:215
本文介绍了创建类对象的指针数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:



创建一个至少四个指向Reader对象的数组。使用New运算符创建至少四个指向派生类对象的指针,并将它们分配给数组。



我不确定如果我做的对不对。 / p>

Reader是基类。 John,David,Daniel,Mark是派生类

  int main(void)
{
* obj [4];

obj [0] = new John();
obj [1] = new David();
obj [3] = new Daniel();
obj [2] = new Mark();

}

这是正确的

解决方案

您的代码正确



sharptooth建议,在分配的 obj [] 上进行 delete 的练习。在C ++ new 分配内存和 delete 解除分配。


Question:

Create an array of at least four pointers to Reader objects. Use the New operator to create at least four pointers to derived class objects and assign them to the array.

I'm not sure If I did it right or not.

Reader is the base class. John, David, Daniel, Mark are the derived class

int main(void)
{
     Reader *obj[4];

    obj[0] = new John();
    obj[1] = new David();
    obj[3] = new Daniel();
    obj[2] = new  Mark();

}

Would this be right???

解决方案

Your code is correct.

And as @sharptooth suggested, make a practice of delete on the allocated obj[]s. In C++ new allocates memory and delete deallocates.

这篇关于创建类对象的指针数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆