C++ 每次调用方法时,自定义类将变量重置回原始值

C++ 每次调用方法时,自定义类将变量重置回原始值,c++,C++,在我的类中,有两个方法负责获取和设置私有变量的值。在类之外的另一个方法中,我调用setter方法并将变量更改为另一个值。它暂时工作,但始终重置为原始值 class storeItem { public: void setPrice(int p) { price = p; } int getPrice() { return price; }

在我的类中,有两个方法负责获取和设置私有变量的值。在类之外的另一个方法中,我调用setter方法并将变量更改为另一个值。它暂时工作,但始终重置为原始值

class storeItem
{
    public:
        void setPrice(int p)
        {
            price = p;
        }
        int getPrice()
        {
            return price;
        }
        storeItem(int p)
        {
            price = p;
        }
    private:
        int price;
}

void changePrice(storeItem item)
{
    int origPrice = item.getPrice();
    item.setPrice(rand() % 10 + 1);
    //The price is correctly changed and printed here.
    cout << "This item costs " << item.getPrice() << " dollars and the price was originally " << origPrice << " dollars." << endl;
}

int main()
{
    storeItem tomato(1);
    changePrice(tomato);
    //This would print out "This item costs *rand number here* dollars and the price was originally 1 dollars." But if I call it again...
    changePrice(tomato);
    //This would print out "This item costs *rand number here* dollars and the price was originally 1 dollars." even though the origPrice value should have changed.
}
类存储项
{
公众:
无效设定价格(INTP)
{
价格=p;
}
int getPrice()
{
退货价格;
}
storeItem(INTP)
{
价格=p;
}
私人:
国际价格;
}
无效更改价格(storeItem项目)
{
int origPrice=item.getPrice();
item.setPrice(兰特()%10+1);
//价格已正确更改并在此处打印。

C++中的CUT

,除非你另外指出,否则函数参数是按值传递的。在你的例子中,你把“代码>存储项< /代码>按值传递给你的函数,所以你正在修改函数体内部的本地副本。对调用方没有影响。你需要通过一个引用:

void changePrice(storeItem& item)
                          ^

语义上,引用只是对象的别名,因此您可以在函数内部考虑<代码>存储项>代码>与调用方中的一个相同。

当调用函数“代码>变更价格< /代码>时,不引用它,也不指向存储项的指针,因此生成了一个副本。

改为通过引用调用:

void changePrice(storeItem& item)
{
     //what you did before
} 

请参阅以获取进一步的参考。

在方法中使用参考:
storeItem&item
的可能重复项