#include <iostream>
#include <string>
#include <vector>
usingnamespace std;
class Person
{
public:
Person();
~Person(){}
void setName(string a)
{
name = a;
}
void setAge(int p)
{
age = p;
}
void addAge()
{
age +=1;
}
void printPerson()
{
cout << "Name: " << name << " age: " << age << endl;
}
private:
int age;
string name;
};
Person::Person()
{
}
class Car
{
public:
Car();
~Car();
void setModel(string c)
{
model = c;
}
void setDriver(Person* p)
{
*driver = *p;
}
void setOwner(Person* p)
{
*owner = *p;
}
private:
string model;
Person *driver;
Person *owner;
};
int main()
{
vector<Person*> people;
//vector<Car> vehicle(100);
string name;
int age;
Person *p1;
cout << "Enter a person or -1 to stop: " << endl;
getline(cin, name);
while(name != "-1")
{
cout <<"Enter Age: " << endl;
cin >> age;
cin.sync();
p1 = new Person;
p1->setName(name);
p1->setAge(age);
people.push_back(p1);
cout << "Enter a person or -1 to stop: " << endl;
getline(cin, name);
}
vector<Person*>::iterator it;
for ( it = people.begin(); it != people.end(); ++it ) {
// For each person, print out their info
it->printPerson();
}
system("PAUSE");
}
Every thing works except this will not compile it was compiling before I was using a vector of pointers and just a vector. Specifically not working now is this line it->printPerson(); Thanks in advance.
1 2 3 4
for ( it = people.begin(); it != people.end(); ++it ) {
// For each person, print out their info
it->printPerson();
}
Why are you using a vector<Person*> instead of just vector<Person>?
But if you do want to use the Person* in the vector then you need to change it->printPerson();
to (*it)->printPerson();
To properly print the actual contents of the class.