无论如何,是否可以使用用户输入的类“项目名称”来访问该项目中的数据?

时间:2019-04-24 15:56:43

标签: c++ class

如何从用户输入的班级名称访问班级数据?

我设置了一个变量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 ;
}

2 个答案:

答案 0 :(得分:1)

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);

答案 1 :(得分:0)

我认为您对对象的工作方式有基本的误解。

string a = "";

只是一个不包含其他字段的字符串对象。它仅保留的数据是您执行cin >> a;时通过输入流读取的数据。

现在,您可以将ab分配给Z.name = a;Z.itemnum = b;,然后再进行cout <<< Z.name;cout << Z.itemnum