C ++列表和指针 [英] C++ lists and pointers

查看:203
本文介绍了C ++列表和指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从事作业,想知道这是什么实际定义为:

I am working on homework and wanted to know what this is actually defined as:

list < NAME > * m_ofList

其中名称来自 struct 像这样:

typedef struct name
{
    int age;
    int height;
} NAME;

我想知道是什么,所以我知道如何插入或访问它: push_back 插入

I want to know what it is so I know how to insert to it or access it: push_back, insert, etc.

所以我现在明白了,但我被卡住,因为某些类型的内存访问:它产生一个分段错误,我一直无法想出这一点。
我需要在哪里初始化我的新列表?它不在构造函数或函数中工作。只是FYI,它是一个私人列表,所以它只能用于成员函数(即m_ofList)。如果任何人想帮助...我可以生成代码。

So I understand this now, but I am stuck because of some type of memory access: it produces a segmentation fault and I have been unable to figure this out. Where do I need to initialize my new list? it doesn't work in constructor or in the functions. Just FYI, it is a private list so it can only be used for member functions (i.e. m_ofList). I can produce code if anyone would like to help...

推荐答案

假设 using namespace std 使用std :: list ,这是一个指向类/ struct NAME的对象列表的指针。要放置对象,首先需要初始化它:

Assuming using namespace std or using std::list, that's a pointer to a list of objects of the class/struct NAME. To put objects in it, first you need to initialize it:

m_ofList = new list<NAME>;

或:

m_ofList = &(some already initialized list of NAME objects);

然后您可以将项目放入其中:

Then you can put items in it:

NAME x;
x.age = 15;
x.height = 150;
m_ofList->push_back(x);
m_ofList->insert(m_ofList->begin(), x);

如果你用动态分配列表 new ,它需要在你完成后被妥善处置:

If you went with dynamically allocating the list with new, it needs to be properly disposed of when you are done with it:

delete m_ofList;

我的问题是,为什么它是一个指针?你可以这样声明它(如你所愿):

My question for you is, why is it a pointer in the first place? You could just declare it (as you should) like this:

list<Name> m_ofList;

然后你不必担心处理它。它将通过范围规则来处理。

Then you wouldn't have to worry about disposing of it. It would be taken care of by scoping rules.

这篇关于C ++列表和指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆