简体   繁体   English

如何正确使用指向类对象的指针的矢量

[英]how to correctly use vector of pointers to objects of class

I wonder why the second part of the following code I wrote doesn't work. 我不知道为什么我编写的以下代码的第二部分不起作用。 I am practicing vector of pointers to class objects. 我正在练习指向类对象的指针的向量。 I tried two ways, one is to define a class object; 我尝试了两种方法,一种是定义一个类对象。 the other is to define a pointer to the object. 另一种是定义一个指向对象的指针。 The second way failed. 第二种方法失败了。

#include <iostream>
#include <vector>

using namespace std;

class A{
    public:
        int id;
        A(int id):id(id){}
};

int main()
{
    vector<A*> A_vec, A_vec2;
    A a(5);
    A_vec.push_back(&a);
    cout << A_vec.size() << "; id " << A_vec[0]->id << endl;


    A *a1;
    a1->id = 5;
    A_vec2.push_back(a1);
    cout << A_vec2.size() << "; id " << A_vec2[0]->id << endl;
}

The second snippet doesn't work because you've never allocated memory for the object, so a1 points nowhere. 第二个片段不起作用,因为您从未为对象分配内存,因此a1指向无处。

A *a1 =  new A(5);

...

// Once you're done with `a1', release the memory.
delete a1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM