Наверное есть больше вариаций. Предложу три.
1) Добавление объекта в контейнер(вектор) с помощью метода контейнера(push_back) и вызова конструктора при создании объекта который будет инициализировать поля.
2) Создание объекта, вызов метода set и добавления объекта в вектор при помощи метода контейнера(push_back, insert, etc).
Здесь демо двух вариаций:
#include <iostream>
#include <vector>
#include <Windows.h>
using namespace std;
class Animal {
string name;
string gender;
int age;
public:
// Default constructor
Animal() {
name = "";
gender = "";
age = 0;
}
// Constructor which can be called when creating an object
Animal(string n, string g, int a) {
name = n;
gender = g;
age = a;
}
void set(string n, string g, int a) {
name = n;
gender = g;
age = a;
}
void const print() {
cout << "Животное: " << name << endl << "Пол: " << gender << endl << "Возраст: " << age << endl;
}
};
int main() {
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
setlocale(LC_ALL, "Russian");
/* Creating a vector container and adding an object by calling the constructor of the Animal class and calling the container-vector method */
vector <Animal> animals;
animals.push_back(Animal("dog", "male", 3));
// Creating an object and calling the set method
Animal cat;
cat.set("cat", "male", 1);
animals.push_back(cat);
// Content of vector
for(auto animal: animals) {
animal.print();
cout << "" << endl;
}
return 0;
}
Третий вариант, вектор определенной длины(трех объектов как вариация).
#include <iostream>
#include <vector>
#include <Windows.h>
using namespace std;
class Animal {
string name;
string gender;
int age;
public:
// Default constructor
Animal() {
name = "";
gender = "";
age = 0;
}
void set(string n, string g, int a) {
name = n;
gender = g;
age = a;
}
void const print() {
cout << "Животное: " << name << endl << "Пол: " << gender << endl << "Возраст: " << age << endl;
}
};
int main() {
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
setlocale(LC_ALL, "Russian");
vector <Animal> animals(3);
animals[0].set("dog", "male", 3);
animals[1].set("cat", "male", 1);
animals[2].set("pig", "female", 5);
// Content of vector
for(auto animal: animals) {
animal.print();
cout << "" << endl;
}
return 0;
}