简体   繁体   English

创建指向 class object 的指针数组

[英]Creating array of pointers to class object

Question:问题:

Create an array of at least four pointers to Reader objects.创建一个至少包含四个指向 Reader 对象的指针的数组。 Use the New operator to create at least four pointers to derived class objects and assign them to the array.使用 New 运算符创建至少四个指向派生 class 对象的指针,并将它们分配给数组。

I'm not sure If I did it right or not.我不确定我是否做对了。

Reader is the base class.阅读器是基础 class。 John, David, Daniel, Mark are the derived class John、David、Daniel、Mark 是派生的 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.正如@sharptooth 建议的那样,在分配的obj[]上进行delete练习。 In C++ new allocates memory and delete deallocates.在 C++ 中new分配 memory 并delete释放。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM