Hi! I've just started with Classes and what I want to do is to create a new instance whenever the user presses x key. For that, I created a vector, but the problem is I can't find the way to add a new element at the end of it. Here's my code:
#include<iostream>
#include<string>
#include<vector>
usingnamespace std;
class Person{
int age;
string name;
public:
Person(){
age=0;
name="\0";}
void setValues(){
cin>>name>>age;
}
void showName(){cout<<name<<endl;}
void showAge(){cout<<age<<endl;}
};
int main(){
vector<Person> People(2);
People[0].setValues();/*This is just for testing*/
People[0].showName();
People[0].showAge();
People[1].showName();
People[1].showAge();
Peolpe.push_back(/*I don't know what to do here*/);
}
Another question, which I guess is really stupid, is why do I get an error if I declare "Person", before main, and define it after main, like this:
class Person; This only allows you to have pointer and references to Person objects. To be able to create Person objects, call its member functions and constructors or in any other way use Person you need to define it before.
you can also use initializer lists, to initialise the object without using the costuctor explicitly: People.push_back({123, "Foo Bar"})
Or, sice I see you are using c++11, you can use emplace_back for the same functionality: people.emplace_back(123, "Foo Bar")
You choose which one of the three you will use.