使用getline c++获取对象的名称
Get the name of an object with getline C++
我想做的是首先问你想知道什么车辆的统计与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;
}
相关文章:
- 如何在C++中获取该对象的类声明中对象的地址?
- 无法获取webot::PositionSensor对象中位置传感器的值
- 最多获取2个对象
- 从 Boost ASIO 获取 epoll 描述符 io_service对象
- 如何在新的派生对象中获取基本对象的数据?
- 如何从 CSV 获取数据并将其存储在 C++ 中的表对象中
- 数组中不同类型的对象并获取每个对象的类型
- push_back通过自行创建的对象获取最后一个元素的向量
- 我可以从列表中获取对象并复制它们,但如何删除我复制的对象?
- 在C++中从内部类对象获取外部类对象
- 如何从 GDI+ 图元文件对象获取原始图元文件字节
- C++ std::队列推送弹出两个不同的对象获取第一个对象
- 尝试从另一个类对象获取值时出现分段错误
- 从元对象获取属性更改通知程序
- 从 Json 对象获取非缩进字符串
- 从套接字对象获取fd或句柄
- (如何)我可以从IWbemClassObject对象获取GUID吗
- 使用不同类中的类对象获取不正确的数据
- OpenCV Mat 对象 - 获取数据长度
- 在 c++ 中,如何从对象获取到静态成员