C ++列表迭代问题 [英] C++ List iteration issue

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

问题描述

我以前有C#的经验,而且我是C ++的新手,我有一个简单的问题.在这段代码中,当我打印a和n的值时,它们应该相等(在我看来),但事实并非如此.我不知道为什么会这样,变量s和* p应该指向同一件事.如果我更改第5行和第6行的顺序,那么事情就变得正确了.我的问题是,为什么s和* p没有指向相同的变量.我认为我在这里缺少一些基本概念.请任何人解释一下

Hi i have previous experience in C#, and i am new to C++, I have a simple question. In this code when i print value of a and n they should be equal (in my opinion) but it is not the case. I wonder why it is so, variable s and *p should be pointing to same thing. If i change the order of line 5 and 6 then things got correct. My question is that why s and *p not pointing to same variable. I think i am missing some basic concept here. Please can any one explain this

void EnterMentorsDataTest()
{
    Supervisor s;
    s.GetEntity();//populate s

    Project prj;
    prj.GetEntity();//populate prj


    slst.push_back(s);
    s.lstProjects.push_back(prj);


    list<Supervisor>::iterator p = slst.begin();
    while(p != slst.end())
    {
        cout<<"----------"<<endl;
        int a = s.lstProjects.size();//a will be 1
        int n = (*p).lstProjects.size();// n will be 0
        p++;
    }
}

推荐答案

值语义.

当您这样做时;
Value semantics.

When you do this;
slst.push_back(s);


您正在使用 copy-constructor [


you''re creating a copy of s using the copy-constructor[^] (one will be generated for you even if you don''t add one. And that copy, will have no items in the list as you''re never adding anything to the copy''s list.

If you add a constructor to Supervisor:

Supervisor(const Supervisor& other)
{
    cout << "Supervisor::Supervisor(COPY_CONSTUCTOR)" << endl;
}



您可以看到它被调用了.

希望这会有所帮助,
弗雷德里克(Fredrik)



you can see it being called.

Hope this helps,
Fredrik


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

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