int main()
{
Base* bp1 = new Base();
Base* bp2 = new Derived();
Derived* dp = new Derived();
cout << (typeid(*bp1) == typeid(Base)) << endl;//1
cout << (typeid(*bp1) == typeid(Derived)) << endl;//0
cout << (typeid(*bp2) == typeid(Base)) << endl;//0
cout << (typeid(*bp2) == typeid(Derived)) << endl;//1
cout << (typeid(*dp) == typeid(Base)) << endl;//0
cout << (typeid(*dp) == typeid(Derived)) << endl;//1
return 0;
}
如果不定义虚函数,影响的是指向子类型的父类型指针
int main()
{
Base* bp1 = new Base();
Base* bp2 = new Derived();
Derived* dp = new Derived();
cout << (typeid(*bp1) == typeid(Base)) << endl;//1
cout << (typeid(*bp1) == typeid(Derived)) << endl;//0
cout << (typeid(*bp2) == typeid(Base)) << endl;//1
cout << (typeid(*bp2) == typeid(Derived)) << endl;//0
cout << (typeid(*dp) == typeid(Base)) << endl;//0
cout << (typeid(*dp) == typeid(Derived)) << endl;//1
return 0;
}
原因很简单,只有父类中定义了虚函数,才能实现运行时绑定。此时使用
Base* bp2 = new Derived();
typeid(*dp)得到的是Derived而不是Base