繁体   English   中英

动态 memory 分配以使用带有 arguments c++ 的构造函数创建对象数组

[英]dynamic memory allocation to create array of objects using constructor with arguments c++

如何使用带参数的构造函数分配对象数组?

我也不知道我能不能? 还是我只需要创建另一个 class 方法来初始化对象?

#include <iostream>
using namespace std;

class Animal {
    string name;
public:
    Animal(){}
    Animal(string name) : name(name) {};
    virtual ~Animal(){}
    Animal(const Animal &other) : name(other.name) {}
    void toSpeak() const { cout << "My name is " << name << endl; }
};

Animal *createAnimal(){
    Animal *a = new Animal("cat");
    return a;
}

int main() {
    Animal *cat = createAnimal();
    cat->toSpeak();
    delete cat;

    cout << "--------------------------"<<endl;
    Animal *pcat = new Animal[5]();

    delete [] pcat;
    return 0;

}

与您对 static arrays 执行此操作的方式相同:

#include <iostream>
#include <string>

class Animal {
 private:
  std::string name;

 public:
  Animal() = default;
  Animal(std::string name) : name(std::move(name)){}
  virtual ~Animal() = default;
  Animal(const Animal &other) : name(other.name){}
  void toSpeak() const { std::cout << "My name is " << name << std::endl; }
};

int main() {
  using namespace std::literals;
  Animal *pcat = new Animal[5]{"Cat1"s, "Cat2"s, "Cat3"s, "Cat4"s, "Cat5"s};

  delete[] pcat;
  return 0;
}

暂无
暂无

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

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