Cha*_*had 2 c++ class identification
我将以示例的形式对此进行说明,以使其更加清晰.
说我有一个动物矢量,我想通过阵列,看看元素是狗还是猫?
class Dog: public Animal{/*...*/};
class Cat: public Animal{/*...*/};
int main()
{
vector<Animal*> stuff;
//cramming the dogs and cats in...
for(/*all elements in stuff*/)
//Something to the effect of: if(stuff[i].getClass()==Dog) {/*do something*/}
}
Run Code Online (Sandbox Code Playgroud)
我希望有点清楚.我知道关于typeid,但是我没有任何Dog对象来比较它,如果可以的话我想避免创建一个Dog对象.
有没有办法做到这一点?提前致谢.
正如其他人所指出的那样,你既不应该使用typeid,也不应该使用dynamic_cast运算符来获得指针指向的动态类型.创建虚函数是为了避免这种肮脏.
无论如何,如果你真的想要这样做,你会这样做(请注意,取消引用迭代器会给你Animal*.所以,如果你这样做,**it你会得到一个Animal&):
for(std::vector<Animal*>::iterator it = v.begin(); it != v.end(); ++it) {
if(typeid(**it) == typeid(Dog)) {
// it's a dog
} else if(typeid(**it) == typeid(Cat)) {
// it's a cat
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,您也可以将typeid运算符应用于自身类型,如上所示.您不需要为此创建对象.另请注意,如果将指针传递给它,则typeid方式不起作用typeid(*it).像这样使用它会给你typeid(Animal*)哪个没用.
类似,dynamic_cast可以使用:
for(std::vector<Animal*>::iterator it = v.begin(); it != v.end(); ++it) {
if(Dog * dog = dynamic_cast<Dog*>(*it)) {
// it's a dog (or inherited from it). use the pointer
} else if(Cat * cat = dynamic_cast<Cat*>(*it)) {
// it's a cat (or inherited from it). use the pointer.
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,在这两种情况下,您的Animal类型应该是多态的.这意味着它必须拥有或继承至少一个虚函数.