简体   繁体   English

在指针向量 c++ 中存储新的 object

[英]Storing new object in pointer vector c++

With the following code i need to store new object in pointer vector.使用以下代码,我需要将新的 object 存储在指针向量中。 I've done it but now it wont show any information about object in loop (where I go trough vector).我已经完成了,但现在它不会在循环中显示有关 object 的任何信息(其中我是 go 槽向量)。 In class Tvrtka (company) I have pointer vector of Zaposlenik(worker).在 class Tvrtka(公司)中,我有 Zaposlenik(工人)的指针向量。 For every object I store it goes to vector.对于每个 object 我将其存储到向量中。

class Tvrtka{
public:
    string oib;
    string naziv;
    string adresa;
    vector<const Zaposlenik*> zaposlenici;
    Tvrtka(){}
    Tvrtka(const string _oib, const string _naziv,const  string _adresa, vector<const Zaposlenik*> _z)

    {
        this->oib=_oib;
        this->naziv=_naziv;
        this->adresa=_adresa;
        for(int i=0;_z.size();i++)
        {
            zaposlenici.push_back(_z[i]);
        }
    }

Main part:主要部分:

vector<const Zaposlenik*>zaposlenici;

    Zaposlenik *z1=new Zaposlenik("Marko", "maric", 20);
    zaposlenici.push_back(z1);

    Tvrtka t1("198","Majur", "2222", zaposlenici);


        for(int i=0;i<zaposlenici.size();i++)
        {


            cout<<zaposlenici[i]->ime;
        }

If I comment t1(object of Tvrtka) it shows me information about worker.如果我评论 t1(Tvrtka 的对象),它会向我显示有关工人的信息。

In this loop在这个循环中

for(int i=0;_z.size();i++)
{
    zaposlenici.push_back(_z[i]);
}

_z.size() is used as loop condition and this is not dependent with i . _z.size()用作循环条件,这与i无关。 This means that if you pass non-empty vector as _z , the loop will go infinitely and it will run out of memory.这意味着如果您将非空向量作为_z传递,则循环将无限循环 go 并且它将用完 memory。

It should be它应该是

for(int i=0;i<_z.size();i++)
{
    zaposlenici.push_back(_z[i]);
}

or simply或者干脆

for(auto& elem : _z)
{
    zaposlenici.push_back(elem);
}

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

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