繁体   English   中英

从数组指针参数设置数组

[英]Setting an array from an array pointer parameter

Zoo::Zoo(Name* name, Location* location, Animal* animals[]) {
    this->name = name;
    this->location = location
 }

我的Zoo类还有一个名为animals的变量,它存储未知数量的Animal对象。

如何在上面的构造函数中设置它?

使用 C++ 容器,而不是原始 C 数组。

#include <vector>

Zoo::Zoo(Name* name, Location* location, const std::vector<Animal*>& animals) {
    this->name = name;
    this->location = location;
    this->animals = animals;
}

使用std::vector你不需要知道有多少动物。 您的类定义如下所示:

class Zoo {
    Name * name;
    Location * location;
    std::vector<Animal *> animals;
    /* ... */
};

如果你想走这条路(我强烈推荐它,我认为大多数 C++ 社区都会同意),你应该查找关于std::vector基本用法的教程,以及其他一些相关类,例如std::liststd::setstd::unordered_set ,它们都有自己的优点/缺点。 我推荐std::vector因为它的行为最接近原始 C 数组的行为,同时仍然可以安全地调整大小。


在 C++ 中,编写复制其他对象的构造函数的最佳方法是使用初始化列表。 那些看起来像这样。

Zoo::Zoo(Name* n, Location* l, std::vector<Animal*> a) : name(n), location(l), animals(a) {}

这里的区别在于Zoo构造函数的参数在构造函数的代码运行之前直接转发给Zoo成员的构造函数。 在这种情况下,由于这就是所有需要完成的工作,因此构造函数无事可做并且留空 ( {} )。

您可以使用 std::vector 如下

#include <vector>

Zoo::Zoo(Name* name, Location* location, std::vector<Animal*> animals) {
    this->name = name;
    this->location = location;
    this->animals = animals;  // where animals is an attribute in your Zoo class
 }

您可以按顺序手动复制动物数组中的每个元素。 但是,这意味着数组中的元素数量是已知的,或者最后一个元素被设置为已知值(例如 NULL)。 然后代码变成:

#include <vector>

Zoo::Zoo(Name* name, Location* location, Animal** animals, size_t nAnimals) {
    this->name = name;
    this->location = location;
    // Animal **animals; // this is the attribute in Zoo
    this->animals = new Animal*[nAnimals];
    for(size_t i = 0; i < nAnimals; i++) {
             this->animals[i] = new Animal(); // assuming default constructor for Animal class 
             memcpy(this->animals[i], animals[i], sizeof(Animal));
    }

为了释放分配的内存,在析构函数(~Animal()) 中使用以下代码

for(size_t i = 0; i < nAnimals; i++)
                 delete this->animals[i]; 
delete[] animals; 

暂无
暂无

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

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