C++中实现多态时怎样判断一个父类指针指向哪一个子类对象?
C++中实现多态时怎样判断一个父类指针指向哪一个子类对象?就像Java中Instanceof()方法,我用typeid做不出来
#include "Person.h"
#include "Student.h"
#include <iostream>
#include <typeinfo>
using namespace std;
int main()
{
Person* p = new Student(1, "小李", MALE, 21, 3, 1);
p->print();
if(typeid(p) == typeid(Student))
{
cout << "Yes" << endl;
}
else
{
cout << "No" << endl;
cout << typeid(new Student(1, "小李", MALE, 21, 3, 1)).name() << endl;
}
delete p;
return 0;
}
定义一个Person* 指针,有多态性可以指向Student类对象,也可以指向Teacher类对象,现在我要想知道当前的
Person* 到底指向那个子类,在C++里有没有什么办法呢?(java中好像有个instanceof方法)
页:
[1]
