C ++循环中的对象引用 [英] C++ Object references in loop cycle

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

问题描述

我试图使用循环创建相同类型的不同对象,然后存储指向链接列表中每个特定对象的指针。问题是,每当一个对象是instanciate,它的指针返回相同的内存地址,它不允许我区分该列表中的每个单独的对象。

I'm trying to create different objects of the same type using a loop, and then storing a pointer to each specific object in a linked list. The problem is, each time an object is instanciate, its pointer return the same memory adress, wich doesn't allow me to differentiate each individual object in that list.

任何解决方案?感谢

我有一个具有以下功能:

I have a function with the following:

    Data dt(10,10,2010);
int p=0;
ifstream fx;
fx.open("utilizadores.txt",ifstream::in);
if(!fx)
{cout << "FX. nao existe!" <<endl;}
string linha;
string nLugar;
int iD=1;

while(!fx.eof())
{
    getline(fx,linha,'\n');
    Utilizador* user;
    if(linha.find(',')==-1 && linha.size()>1)
    {
        cout<<"Entrou no vector"<<endl;
        string nlugar(linha.substr(0, linha.size()));
        nLugar=nlugar;

    }

      else
    {
        int inic=0;
        int pos=linha.find(',',inic);
        string nick(linha.substr(inic,pos-inic));
        pos++;
        inic=pos;
        pos=linha.find(',',inic);
        string email(linha.substr(inic,pos-inic));
        user=new Utilizador(dt,iD,nick,email);
        cout<<&user<<endl;
        cout<<user->clone()<<endl;
        }
    fx.close();
    }

链接列表在类语句中声明

The linked list is declared in the class statement

推荐答案


cout<<&user<<endl;

应为:


cout<<user<<endl;

& user是本地变量Utilizador *的地址,它保持不变。用户变量值本身是你需要的指针,并且在每次迭代时它应该是不同的。

&user is address of local variable Utilizador*, which remains the same. user variable value itself is the pointer you need, and it should be different on every iteration.

这篇关于C ++循环中的对象引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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