当我在c ++中使用带有类的向量时会发生什么

时间:2015-08-21 20:07:13

标签: c++ vector

我有类Person并创建一个Person类型向量。我想知道帽子发生在我用向量索引调用Person类型函数时。这是否存储了数组中的对象或者请事先简单地解释一下。

#include<iostream>
#include<string>
#include<vector>
using namespace std;
class Person
{
int age;
string name;
public:
Person(){};
void getdata()
{
    cout << "Enter your name: ";
    getline(cin >> ws, name);
    cout << "Enter your age: ";
    cin >> age;
}
void showdata()
{
    cout << "\nHello " << name << " your age is " << age;
}
};
void main()
{
vector<Person> myVector(3); 
unsigned int i = 0;
for (i; i < 3; i++)
    myVector[i].getdata();//Does this create & save an objects in that  location   Please explain briefly, Thanks
for (i=0; i < 3; i++)       //What if I do this like
                            /*for (i=0; i < 3; i++)
                                { Person p;
                                myVector.puskback(p); }
                                or what if I want a new data then what??*/

    myVector[i].showdata();
system("pause");
}

2 个答案:

答案 0 :(得分:4)

不,它不会创建对象。创建矢量时创建所有对象。它做什么,它在已构造的对象上调用getdata()。 您可以按照建议的方式进行回击,在这种情况下,您最初要创建一个空向量(现在您正在创建一个包含3个元素的向量)

答案 1 :(得分:1)

考虑

class A
{
public:
    A(){}
    foo(){}
};
...
int main()
{
     std::vector<A> v1(3);
     //this creates a vector with 3 As by calling the empty constructor on each
     //means means you can readily manipulate these 3 As in v1
     for(int i = 0; i < v1.size(); i++)
         v1[i].foo();

     std::vector<A> v2;
     //this creates a vector of As with no pre-instantiated As
     //you have to create As to add to the vector
     A a1;
     v2.push_back(a1);
     //you can now manipulate a1 in v2
     v2[0].foo(); 

     //You can add to v1 after having initially created it with 3 As
     A a2;
     v1.push_back(a2);

     //You have all the flexibility you need.
}