首页 > 解决方案 > 我的成员函数旨在更改类中的特定成员数据实际上并没有更改它

问题描述

我已经开始编写一个程序来制作饮料并根据不同的变量(配料、大小)计算它的价格。但是,当尝试编写一个名为 setSize 的函数来更改特定饮料的大小时,跟踪饮料大小的布尔值保持不变。

这是我的课:

class Boba {
    const double basePrice = 3.5;
    const double largeDrinkPrice = 1.;
    const double toppingPrice = 0.3;
private:
    string flavor;
    int toppings;
    bool isLarge;
    double price;
    void updatePrice();
public:
    Boba(string flavor1, int toppings1, bool isLarge1) {
        flavor = flavor1;
        toppings = toppings1;
        isLarge = isLarge1;
    }
    void setFlavor(string flavor);
    void setSize(bool isLarge);
    bool setToppings(int toppings);
    double getPrice();
    void printDrink();
};

我在我的主要功能中调用它:

int main(int argc, const char* argv[])
{

    std::cout << std::fixed << showpoint;
    std::cout << std::setprecision(2);

    Boba myDrink1("almond milk tea", 2, false);

    myDrink1.printDrink();

    cout << "Changing myDrink1 to a large size." << endl;
    myDrink1.setSize(true);
    myDrink1.printDrink();
    cout << endl;

    return 0;
}

我的打印饮料功能,以防这里出现问题:

void Boba::printDrink()
{
    cout << "Boba with flavor " << flavor << ", " << toppings << " toppings";
    if (isLarge)
        cout << ", size large";
    cout << ". $" << getPrice() << endl;
}

double Boba::getPrice()
{
    updatePrice();
    return price;
}

这就是我遇到问题的地方,在我的 setSize 函数和 updatePrice 函数中:

void Boba::updatePrice()
{
    if (isLarge) {
        price = largeDrinkPrice + (toppings * toppingPrice) + basePrice;
    }
    else {
        price = (toppings * toppingPrice) + basePrice;
    }
}

void Boba::setSize(bool isLarge)
{
    isLarge = true;
    updatePrice();
}

编辑:似乎当它返回更新价格函数时,它对于 isLarge 变为 false。

标签: c++

解决方案


这个功能真的很奇怪。

void Boba::setSize(bool isLarge) {
    isLarge = true; // you set the function parameter to true here, not the class member variable isLarge
    updatePrice();
}

使用 this-> 明确告诉编译器使用哪个变量:

void Boba::setSize(bool isLarge) {
    this->isLarge = isLarge;
    updatePrice();
}

为了避免这样的错误,人们经常为私有变量使用自定义前缀,不要将它们与函数参数混合,因为它们往往具有相同的名称。例如 _isLarge 或 m_isLarge(Qt 风格)。然后使用 this-> 是没有必要的,并且使代码更清晰和更具可读性。


推荐阅读