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

use*_*214 2 c++

在我的课堂上,我有两个方法负责获取和设置私有变量的值.在另一个类之外的方法中,我调用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.
}
Run Code Online (Sandbox Code Playgroud)

我确定我犯了一个愚蠢的初学者错误,我提前感谢任何帮助!:)

jua*_*nza 5

在C++中,除非另有说明,否则函数参数将按值传递.在您的示例中,您将storeItemby值传递给函数,因此您正在修改函数体内的本地副本.呼叫方没有任何影响.你需要传递一个参考:

void changePrice(storeItem& item)
                          ^
Run Code Online (Sandbox Code Playgroud)

从语义上讲,引用只是对象的别名,因此您可以storeItem将函数内部视为与调用方的内部相同.