[英]dynamic memory allocation to create array of objects using constructor with arguments c++
How can I allocate an array of objects using a constructor that takes an argument?如何使用带参数的构造函数分配对象数组?
I don't even know if I can?我也不知道我能不能? Or do I just have to create another class method to initialize the objects?
还是我只需要创建另一个 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;
}
The same way you'd do it for static arrays:与您对 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.