当我在C ++中对类使用vector时会发生什么

赛飞369

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在C ++中,当我对-128,127范围以外的整数使用static_cast <char>时会发生什么?

当我在Bash脚本中对函数使用`&`时会发生什么?

当我分配大于字节的值时会发生什么?

当我们在@Bean中创建新类并在另一个@Bean中在@Bean中使用时会发生什么?

当我在C ++中对未初始化的指针调用“删除”时会发生什么?

当我定义一个抽象类而不是声明时会发生什么。

当我使用'|'时会发生什么 或'<',c ++

当我们在C#中访问字符串的'Length'属性时会发生什么?

当我多次调用requestAnimationFrame时会发生什么

当我们在C ++中更改字符串的值时会发生什么

当我在Ionic 2中导入未使用的附件时会发生什么?

当我在Xcode IDE中“保存”时会发生什么

在名称对象绑定方面,当我在python中创建诸如c = [1]的列表时会发生什么?

春季:当我们将@ComponentScan移到包中的另一个类时会发生什么?

当我在C ++中存储指向按值传递参数的指针时会发生什么?

当我们在Python的类中给出函数定义时会发生什么

当我在python中写“ a,b,c = [[],] * 3”时会发生什么?看来a,b,c是同一对象

发生“注入类名称”时会发生什么?(C ++)

当我在同一指针中两次使用malloc()时会发生什么?

当我放弃对iOS 6的支持时会发生什么?

当我截断正在使用的文件时会发生什么?

当我们在同一类中创建类的实例时会发生什么?

当我使用多个模拟时间时会发生什么?

当我调用“ BufferStrategy.show()”时会发生什么?

当我尝试使用空的默认构造函数创建对象但在 ANSI C++ 中添加括号时会发生什么?

当我取消订阅 Observable 链时会发生什么?

当我在不相互接壤的多边形上使用 GeoPandas 中的 .dissolve 函数时会发生什么?

当我们在 C 中使用字符而不是整数来定义数组时会发生什么?

当我们在 C++ 中使用“while”时会发生什么转换?