使用getline c++获取对象的名称

Get the name of an object with getline C++

本文关键字:取对象 获取 getline c++ 使用      更新时间:2023-10-16

我想做的是首先问你想知道什么车辆的统计与getline

像这样:

cout & lt; & lt;"写一个车名"<<endl;
如果用户写入Mustang,则调用Mustang。mostrarMensaje,但如果我想要更自动的东西,我不想使用

  #include <cstdlib>
  #include <iostream>
  #include <string> 
  using std::cout;
  using std::endl;
  using std::string;
  using namespace std;
  class Vehiculos 
  {
        public:
        int suGas;
        int suVelocidad;
        int suCondicion;
        int suTipo;  
        void mostrarMensaje()
        {
             cout << "Estadisticas de su vehiculo!" <<  endl;
             cout << "Gas:" << suGas << endl;
             cout << "Velocidad maxima:" << suVelocidad << endl;
             cout << "Condicion:" << suCondicion <<  endl;
             cout << "Tipo:" << suTipo <<  endl;
        } 
  };
  int main(int argc, char *argv[])
  {
      Vehiculos Mustang;
      Mustang.suGas = 100;
      Mustang.suVelocidad = 250;
      Mustang.suCondicion = 100;
      Mustang.suTipo = 2;
      Mustang.mostrarMensaje();
      system("PAUSE");
      return EXIT_SUCCESS;
  }

当一个c++程序被编译成汇编程序时,编译器会丢弃大量的信息。一些语言有一个叫做反射的特性,类名等信息在运行时是可用的。c++并没有内置这个功能,但是你可以在它的基础上实现一个反射系统。

反射是一个相当高级的主题,可能比你想要的要多一点——尽管知道它的存在是值得的。一种更简单的方法可以完成这里的工作,将字符串用作进入某种数据结构的键,例如具有指向基类Vehiculos的指针的std::unordered_map,您可以通过名为mostrarMensaje的虚方法从中派生Mustang

使用我上面提到的方法(多态性)的一些伪代码(不保证可以编译):

// Abstract base class
class Vehiculos
{
  // Look up virtual destructors if you don't understand why this is here.
  virtual ~Vehiculos() { /*...*/ }
  // Pure virtual method
  virtual void mostrarMensaje() = 0;
};
class Mustang
{
  virtual ~Mustang() { /*...*/ }
  virtual void mostrarMensaje() 
  {
    /* Implement mustang specific logic here */
  }
};
class F150
{
  virtual ~F150() { /*...*/ }
  virtual void mostrarMensaje() 
  {
    /* Implement F150 specific logic here */
  }
};
int main(int argc, char *argv[])
{
  // Ensure at least one parameter was passed to the program 
  //   (first argument will always be the program's name)
  if(argc < 2)
  {
    // Print an error message
    return -1;
  }
  std::unordered_map<std::string, Vehiculos*> vehicles;
  vehicles.insert("Mustang", new Mustang);
  vehicles.insert("F150", new F150);
  auto find_it = vehicles.find(argv[1]);
  if(find_it != vehicles.end())
  {
    (*find_it)->mostrarMensaje();
  }
  else
  {
    // User entered an invalid vehicle name, do something about it
  }
  return 0;
}