首页 > 解决方案 > 在尝试从单独的类更新变量时,我是否需要在这种情况下使用指针?

问题描述

因此,我的程序旨在接受用户的输入以创建具有多个属性(变量)的对象,并将这些对象放入向量中。我在能够更改相关特定项目的数量方面遇到特殊问题。无论我从 main.cpp 调用该函数多少次,它都保持不变。

class ClassA {
    public:
        void SetQuantity(int quantityToGet);
        ...
    private:
        int itemQuantity;
        ...
};

void ClassA::SetQuantity(int quantityToGet) {
    itemQuantity = quantityToGet;
}

class ClassB {
    public:
        ClassB();
        void UpdateItemQnty();
        int FindItemLoc(string targetItem);
        ...
    private:
        vector<ClassB> itemsInVector;
        ...
};

    void ClassB::UpdateItemQnty() {
        ClassA currItem;
        string targetName;
        int newQuantity;
        int itemLoc = -1;

        cout << "Enter the item name: ";
        getline(cin, targetName);
        itemLoc = FindItemLoc(targetName);

        cout << "Enter the new quantity: ";
        cin >> newQuantity;
        cin.ignore();

        if (itemLoc > -1) {
            currItem = itemsInVector.at(itemLoc);
            currItem.SetQuantity(newQuantity);   // FIXME (???)
        }
        else {
            cout << "Item not found in vector. Nothing modified." << endl;
        }
    }

我没有收到任何错误,而且我没有提到或显示定义/声明的功能都可以正常工作。我想我需要使用指针,但我不确定如何。

谢谢你

标签: c++

解决方案


我可以在您的代码中看到两件奇怪的事情:

  • 您正在为 ClassA 对象分配 ClassB 对象(在 setQuantity 调用之上)。那应该会出错,但我想您在帖子中打错了...

  • 从列表中检索数据时,您将其复制到局部变量 currItem!因此,您只更改本地副本,而不是列表中的数据。

在这种情况下,将 currItem 声明为引用可以解决问题,但引用对象的声明需要赋值:

ClassA &currItem = itemsInVector.at(itemLoc);
currItem.SetQuantity(newQuantity);

推荐阅读