C ++指针引用指针,类和指针列表,奇怪的返回

时间:2013-04-01 01:41:01

标签: c++ list pointers return-by-reference

我有一个程序,它在列表中存储类和结构集。

它执行以下操作:

  1. 通过引用将输入(int),迭代器,列表和指针传递给函数check()
  2. 迭代列表,直到找到迭代器的数据和输入
  3. 之间的匹配
  4. 将指针设置为迭代器的位置
  5. 返回true或false,具体取决于是否找到匹配项。
  6. 我的问题是,当我在功能检查中调用函数display()时,无论是来自it->display()还是Ptr->display(),它都能正常工作。但当它通过引用传回时,我试图显示它。它打印垃圾。

    //it is the iterator, l is the list, Ptr is the passed pointer
    template<class T, class T2, class P>
    bool Inspection::check(int input, T it, T2 l, P * &Ptr)
    {
        for(it = l.begin(); it != l.end(); ++it){   //Iterates through list using iterator
            if (it->checkExists(input)){        //if input == iterator class's data
                Ptr = &*it;
    
                //Display data - ERROR CHECKING//
                it->display();          
                Ptr->display();
    
                return true;
            }
        }
        return false;
    }
    

    checkExists是一个函数,它与正在迭代的类中的私有数据进行比较,例如

    bool Property::checkExists(int input)
    {
        if (input == ID)
            return true;
        return false;
    }
    

    display也很简单

    void Property::display()
    {
        //Prints out property info
        cout << ID << ";" << address << ";" << landTypes[type] << ";" << price << endl;
    }
    

    标准调用是(p是我之前在程序中调用的Property类的列表)

    int input;
    Property * temp; //Pointer to a class temp
    list<Property>::iterator pIT;
    
    cin >> input;
    
    
    while(!check(input, pIT, p, temp)){
        ...
    }
        temp->display();
    

    典型的输出是(前两个是函数内的调用并且正确,第三个是来自函数外部的temp->display();调用。

    1001;5/10 Northfields Ave, North Wollongong, NSW 2500;Townhouse;280000
    1001;5/10 Northfields Ave, North Wollongong, NSW 2500;Townhouse;280000
    13;�������\314���@�ve, North Wollongong, NSW 2500;Townhouse;280000
    

    编辑:对不起,我链接了错误的显示功能()。编辑过的代码

1 个答案:

答案 0 :(得分:2)

不考虑WhozCraig指出的设计问题,在您提供的代码中打印垃圾的问题如下:

 template<class T, class T2, class P>
 bool Inspection::check(int input, T it, T2 l, P * &Ptr)
                                         ^^^^

您正在通过值而不是引用传递l,因此您将返回指向临时变量的指针,当您在方法之外取消引用它时,该临时变量将不存在。如果你修改代码如下,它应该开始为这个特定的问题工作,虽然它确实需要重新设计:

template<class T, class T2, class P>
bool Inspection::check(int input, T it, T2 &l, P * &Ptr)     
相关问题