gpt4 book ai didi

c++ - 无论如何使用用户输入的类项目名称来访问该项目中的数据?

转载 作者:行者123 更新时间:2023-11-28 04:19:17 25 4
gpt4 key购买 nike

如何从用户输入的类名访问类数据?

我设置了一个变量 string a; ,当我尝试返回类似 a.namea.price 的东西时,它不会打印数据。在下面的示例中假设用户输入 Z

Z.name = "Milk" ; 
Z.price = 2 ;
Z.itemnum = 26 ;

string a = "";
int b;

while (a != "0") {
cout << "Enter the item letter: " ;
cin >> a ;
cout << "Enter an item quantity: ";
cin >> b;
cout << "You got " << b << " things of " << a.name << endl;
cout << a ;
}

最佳答案

C++ 并不像您想象的那样工作。变量名仅在代码中使用,在编译过程中会丢失。而且您当然不能将字符串按原样视为变量名。

对于您正在尝试的内容,您需要自己执行名称到对象的映射。您可以为此使用 std::map,例如:

#include <iostream>
#include <string>
#include <map>

class Item
{
std::string name;
double price;
int itemnum;

void set(std::string newName, double newPrice, int newItemNum) {
name = newName;
price = newPrice;
itemnum = newItemNum;
}
};

std::map<std::string, Item> items;

items["Z"].set("Milk", 2, 26);
// other items as needed...

std::string a;
int b;

do {
std::cout << "Enter the item letter: ";
std::cin >> a;
if (a == "0") break;
auto iter = items.find(a);
if (iter != items.end()) {
std::cout << "Enter an item quantity: ";
std::cin >> b;
std::cout << "You got " << b << " things of " << iter->second.name << std::endl;
}
else {
std::cout << "There is no item letter of " << a << ", try again" << std::endl;
}
}
while (true);

关于c++ - 无论如何使用用户输入的类项目名称来访问该项目中的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55834148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com