c++ - 在尝试从单独的类更新变量时,我是否需要在这种情况下使用指针?
问题描述
因此,我的程序旨在接受用户的输入以创建具有多个属性(变量)的对象,并将这些对象放入向量中。我在能够更改相关特定项目的数量方面遇到特殊问题。无论我从 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;
}
}
我没有收到任何错误,而且我没有提到或显示定义/声明的功能都可以正常工作。我想我需要使用指针,但我不确定如何。
- 在收到基于回复的回复后,我可能会删除此内容
谢谢你
解决方案
我可以在您的代码中看到两件奇怪的事情:
您正在为 ClassA 对象分配 ClassB 对象(在 setQuantity 调用之上)。那应该会出错,但我想您在帖子中打错了...
从列表中检索数据时,您将其复制到局部变量 currItem!因此,您只更改本地副本,而不是列表中的数据。
在这种情况下,将 currItem 声明为引用可以解决问题,但引用对象的声明需要赋值:
ClassA &currItem = itemsInVector.at(itemLoc);
currItem.SetQuantity(newQuantity);
推荐阅读
- mysql - 如何在 SQL 脚本中传递预定义的值?
- c# - wpf界面元素被ocx控件覆盖
- postgresql - Activemq postgresql 在 activemq_msgs 表中将消息详细信息和内容记录为 JSON
- c - 如何在 x86_64 中使用 clang-8 的“影子调用堆栈”功能?
- javascript - iOS 通用链接在 Twitter 应用程序中不起作用,但 android 应用程序链接有效
- php - 在 PHP 中使用 jquery ajax 提交条件表单元素
- node.js - 如何使用 Jest 和 Enzyme 在构造函数中测试组件参数
- python - PySpark 将空字符串转换为 null 并在 Parquet 中写入
- r - 使用 R 列出和访问 owncloud 公共文件夹中的文件
- regex - 正则表达式在 WSO2 中无法正常工作,但在 Java 正则表达式测试器上给出了正确的响应