问题描述
我正在尝试创建一个包含“Person”对象的向量。当我不使用向量然后实例化人们以显示结果时,它工作正常。我的 C++ 生锈了,我需要创建一个指针吗?
#include <iostream>
#include <string>
using namespace std;
#include <vector>
#include <ostream>
class Person {
private:
int age;
string name;
public:
int getAge() {
return age;
}
string getName() {
return name;
}
void setAgeName(int a,string n) {
age = a;
name = n;
}
};
int main() {
vector<Person> people;
people[0].setAgeName(49,"Dudeman");
cout << people[0].getName() << endl;
cout << people[0].getAge() << endl;
return 0;
}
结果是一个空白的终端,如果我把main中所有的vector业务都去掉,把它当作一个单一的对象,它工作正常。一定是我遗漏了一些简单的东西。
解决方法
people
向量还没有大小。您需要 push_back
一个 Person
对象:
Person person;
vector<Person> people;
person.setAgeName(49,"Dudeman");
people.push_back(person);