c++ - 如何在c++中检查对象类型

标签 c++ oop inheritance

例如我们有一个 Animal 类,并且我们创建了一些其他类,例如 Lion 类,Tiger 类等。我已经制作了 Animal 类的列表,我想遍历该列表并根据列表中每个成员的类的类型来处理该列表。

Class Animal
Class Tiger :: public Animal{}
Class Lion :: public Animal{}
list<Animal> l;
Tiger T;
Lion L;
l.push_back(T); l.push_back(L);
if the top member of the list is Tiger print"ITs a tiger"
else print"something"

简单来说,我想检查创建的实例的类型。我不知道该怎么做。

最佳答案

这称为RTTI这不是良好的编码习惯。

话虽这么说,如果你绝对想知道一个类的类型,你可以这样做

if (typeid(myanimal) == typeid(Tiger)) {
    // Do something tiger-like
}

对于您的情况,我建议是为所有Animal提供一个通用接口(interface)。 ,例如 sayHello()方法。你会有

class Animal {
    void sayHello() = 0;
    // Other things
}

Tiger这将是

Tiger::sayHello() {
    cout << "Hello I'm a Tiger!" << endl;
}

然后,从您的vector<Animal*> (需要使用指针)只需调用

myAnimal->sayHello();

关于c++ - 如何在c++中检查对象类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12998182/

相关文章:

c++ - 为什么 C++ 不让基类实现派生类的继承接口(interface)?

c++ - 带三点参数的函数

c++ - undefined reference 错误 - MPI 编译

c++ - 关于Qt的初学者问题

r - R 中的对象可以有多个类吗?

c# - 纯抽象类和接口(interface)之间的区别

c# - 保存派生类的集合实例的基类

c++ - 编译时的整数值

c# - 覆盖基类的实现,使得从继承的基类函数调用也调用被覆盖的函数

c# - 如何在派生类时更改常量或静态变量的值?