You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++ Vector中修改对象值异常:游戏库存系统Quantity更新不生效

解决C++库存系统中Item数量无法保存的问题

这种情况我在做游戏库存系统时也踩过坑,大概率是对象拷贝或引用使用不当导致你修改的是临时副本,而非Inventory中存储的实际对象。下面我拆解几个最常见的问题点和对应的修复方案:


1. 遍历Inventory时误用值拷贝而非引用

这是最容易犯的错误!如果你的添加函数是这样遍历Item的:

void Inventory::addItem(Item item) {
    bool itemExists = false;
    // 这里的i是容器中Item的副本,修改它不会影响原对象
    for (auto i : items) {
        if (i.getId() == item.getId()) {
            i.setQuantity(i.getQuantity() + 1);
            itemExists = true;
            break;
        }
    }
    if (!itemExists) {
        items.push_back(item);
    }
}

遍历的时候用auto i : items会创建每个Item的临时副本,你修改的只是这个副本,Inventory容器里的原Item完全没变化。

修复方案:遍历的时候使用引用,直接操作容器里的原对象:

void Inventory::addItem(const Item& item) { // 用const引用传参,避免不必要的拷贝
    // 使用auto& i获取原对象的引用
    for (auto& i : items) {
        if (i.getId() == item.getId()) {
            i.setQuantity(i.getQuantity() + 1);
            return; // 找到后直接返回,不用继续遍历
        }
    }
    // 不存在则添加新Item
    items.push_back(item);
}

2. Item类的setQuantity函数实现错误

有时候问题出在Item本身的setter函数上,比如不小心创建了局部变量覆盖成员变量:

// 错误的实现
class Item {
private:
    int quantity;
    int id;
public:
    void setQuantity(int q) {
        int quantity = q; // 这里定义了局部变量,根本没修改成员变量!
    }
    int getQuantity() const { return quantity; }
    int getId() const { return id; }
};

修复方案:确保setter正确访问成员变量:

class Item {
private:
    int quantity;
    int id;
public:
    Item(int itemId, int initialQty) : id(itemId), quantity(initialQty) {}

    void setQuantity(int q) {
        quantity = q; // 直接修改成员变量,或者用this->quantity = q;
    }
    int getQuantity() const { return quantity; }
    int getId() const { return id; }
};

3. 用指针存储Item时未正确解引用

如果你的Inventory存储的是Item指针(比如std::vector<std::unique_ptr<Item>>),修改时必须解引用指针才能操作实际对象:

// 错误示例:遍历指针时用了值拷贝,可能导致修改失效
void Inventory::addItem(const Item& item) {
    for (auto ptr : items) {
        if (ptr->getId() == item.getId()) {
            ptr->setQuantity(ptr->getQuantity() + 1);
            return;
        }
    }
    items.push_back(std::make_unique<Item>(item.getId(), item.getQuantity()));
}

修复方案:遍历指针时使用引用,确保修改的是容器里的指针指向的对象:

void Inventory::addItem(const Item& item) {
    for (auto& ptr : items) { // ptr是指针的引用
        if (ptr->getId() == item.getId()) {
            ptr->setQuantity(ptr->getQuantity() + 1);
            return;
        }
    }
    items.push_back(std::make_unique<Item>(item.getId(), item.getQuantity()));
}

先按这几个方向排查,基本能解决问题。如果还有疑问,可以把你的Inventory和Item类的核心代码贴出来,我再帮你细化分析。

内容的提问来源于stack exchange,提问作者thomas wright

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:35:55