c++ - 我的成员函数旨在更改类中的特定成员数据实际上并没有更改它
问题描述
我已经开始编写一个程序来制作饮料并根据不同的变量(配料、大小)计算它的价格。但是,当尝试编写一个名为 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。
解决方案
这个功能真的很奇怪。
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-> 是没有必要的,并且使代码更清晰和更具可读性。
推荐阅读
- c - 读取调试对象内存时访问被拒绝
- kubernetes - 我可以从 OVH 云提供商将 OVH 负载均衡器连接到我的 Kubernetes 集群吗
- android - 完全用c开发应用程序
- excel - vba 宏:循环上的备用值显示并限制当前区域的选择
- flutter - 将颤动主题颜色更改为黑色时出错
- java - Apache POI 出现错误,无法读取使用 FileInputStream 传递的文件
- xml - 根据条件 odoo 11 隐藏一份报告打印
- get - 如何在 GET 请求中使用国家/地区参数对加利福尼亚进行地理编码
- utf-8 - UTF-8 解码器应该如何正确处理无效的代码点(代理,大于 0x10ffff)?
- php - 如何使用 PHP 从 MySQL 中获取数组