我有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");
}

最佳答案

考虑

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.
}

关于c++ - 当我在C++中对类使用vector时会发生什么,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32148500/

10-10 16:56
查看更多