我想做的事情是首先询问你想用getline知道哪些车辆的统计数据
这样的事情:
cout<< "写一个车辆名称" << 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;
}
答案 0 :(得分:2)
当c ++程序编译成程序集时,编译器会丢弃大量信息。某些语言具有名为reflection的功能,其中诸如类名之类的信息在运行时可用。 c++ does not have this built in,但你可以在它上面实现一个反射系统。
反思是一个相当高级的主题,可能比你正在寻找的更多 - 虽然值得知道它存在。可以在这里完成工作的一种更简单的方法是将字符串用作某种数据结构的键,例如std::unordered_map
,其中包含指向您从中派生的基类Vehiculos
的指针Mustang
使用名为mostrarMensaje
的虚拟方法。
使用上面提到的方法(polymorphism)的一些伪代码(不保证编译):
// 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;
}