c++指针引用,类和指针的列表,奇怪的返回
C++ Pointer by Reference, lists of classes and Pointers, wierd return
我有一个程序,它在列表中存储类和结构的集合。
执行以下操作:
- 通过引用传递一个输入(一个
int
)、一个迭代器、一个列表和一个指针到函数check()
- 迭代列表,直到找到迭代器的数据与输入 之间的匹配。
- 将指针设置为迭代器的位置
- 返回true或false,取决于是否找到匹配项。
我的问题是,当我从函数检查内调用函数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
编辑:对不起,我链接了错误的显示函数()。编辑代码更新
不考虑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)
相关文章:
- 为什么这个 std::queue/指向结构的指针列表直到 List.Size() == 0 才释放内存?
- 什么更好?返回对象指针列表?或返回指向对象列表的指针?
- 如何将共享指针列表传递到pybind11中的c++对象
- C++:如何初始化包含具有给定键的指针列表的映射
- 使用继承的指针列表复制构造函数或重载运算符=
- 我应该如何在工厂类中存储弱指针列表?
- Qt单元测试:指针列表上的QCOMPARE函数
- 如何正确释放要配对的指针列表?
- 如何在 c++ 上对指针列表进行排序
- 从地图复制到指针列表
- 我对C 中共享指针列表进行排序的功能未完成类型
- const_iterator引用的指针列表
- 在 c++ 中生成字符串到 std::指针列表的映射
- 访问链表中的结构(带有指向其子实现的指针列表的树)
- 有没有办法使用基于范围的迭代器来迭代对指针列表值的引用?
- 使用迭代器指针 (C++) 从对象指针列表中删除元素
- 无法列出定制类型的指针列表
- 创建指针列表的正确范例是什么
- 如何将指向指针列表的私有指针作为 const 返回
- C++填充指向指针**列表的指针,该列表指向指针地址