Hey guys, I'm pretty new to pointers and I'm having some trouble with my assignment. This is the problem:
Write a small program using a vector of pointers to Person objects. Ask the user how many Person objects they want to create. Read data and create Person objects and assign their pointers to the vector. Display each object in the vector.
I wrote some code but I'm having difficult understanding how to do it. If anyone can help put me in the right direction, I would appreciate it.
This is my code so far:
#include <iostream>
#include <string>
#include <vector>
usingnamespace std;
#include "person.h"
int main()
{
int numOfPeople;
string name;
int age;
cout << "Please enter the number of people you wish to add: ";
cin >> numOfPeople;
vector<Person*> people(numOfPeople);
for (int i = 0; i < numOfPeople; i++)
{
cout << "Please enter name: ";
cin >> name;
cout << "Please enter age: ";
cin >> age;
people[i] = Person(name, age);
}
cout << "Please press enter once or twice to continue...";
cin.ignore().get(); // hold console window open
return EXIT_SUCCESS; // successful termination
}
#include <iostream>
#include <string>
usingnamespace std;
/* A class that consists of a persons' name and age
*/
class Person{
public:
/* constructs a Person object with parameters
parameter personName = name
parameter personAge = age
*/
Person(string personName, int personAge);
/* constructs a Person object with default
parameters
*/
Person();
/* sets the name of the person
parameter newName = new person name
*/
void setName(string newName);
/* sets the age of the person
parameter newAge = new person age
*/
void setAge(int newAge);
/* gets the name of the person
and returns it
*/
string getName();
/* get the age of the person
and returns it
*/
int getAge();
private:
string name;
int age;
};
#include <iostream>
#include <string>
usingnamespace std;
#include "person.h"
Person::Person(string personName, int personAge)
{
name = personName;
age = personAge;
}
Person::Person()
{
age = 0;
}
/*
function for assigning name to newName in class Person
*/
void Person::setName(string newName)
{
name = newName;
}
/*
function for assigning age to newAge in class Person
*/
void Person::setAge(int newAge)
{
age = newAge;
}
/*
function to return the name stored in Person
*/
string Person::getName()
{
return name;
}
/*
function to return the age stored in Person
*/
int Person::getAge()
{
return age;
}