C++:无法通过传递给查找器函数来重新分配 null 初始化的对象指针


#include <vector>
#include <iostream>
class IntObj {
  public:
    int num;
    IntObj(int num): num(num) {}
};
bool findNum(int num, IntObj* dst, std::vector<IntObj*> intobjs) {
    for(int i=0; i<(int)intobjs.size(); i++) {
        if (intobjs[i]->num==5) {
            dst = intobjs[i];
            return true;
        }
    }
    return false;
}
int main() {
    std::vector<IntObj*> intobjs;
    for(int i=0; i<10; i++) {
        IntObj* io = new IntObj(i);
        intobjs.push_back(io);
    }
    IntObj* ioptr = NULL;
    findNum(5, ioptr, intobjs);
    std::cout<<ioptr<<std::endl;
    return 1;
}

这是一个测试程序,用于为更大的程序重现我的错误。即使 findNum 函数进入 if 语句 dst 也不会从 NULL 变为 intobjs[i]。

我这样做是因为我想从函数调用中做两件事:1. 确定是否在列表中找到对象2. 如果找到对象,将对象存储到 DST 指针

为什么这不重新分配指针变量?另外,如果有更好的方法,请告诉我。

dst确实会改变,但ioptr不会。这是两个具有两个值的不同变量,尽管dst最初设置为 ioptr 的值。

您还需要通过引用传递它以更改ioptr

bool findNum(int num, IntObj*& dst, std::vector<IntObj*> intobjs)

最新更新