谁能给我解释一下为什么这段代码打印Base,Derived,但是如果我省略了Base中的f函数,就会打印Base,Base?
#include <iostream>
#include <cstdio>
using namespace std;
class Base;
void testClassType (Base& b);
class Base
{
virtual void f(){};
};
class Derived :public Base
{
};
int main ()
{
Base b;
Derived d;
testClassType(b);
testClassType(d);
}
void testClassType(Base& b)
{
cout<<endl<<"It is:"<<typeid(b).name();
}发布于 2011-01-17 07:58:14
根据typeid的定义,它返回多态类型的表达式的动态类型和非多态类型的表达式的静态类型。
多态类型是至少具有一个虚函数的类类型。
在本例中,当您调用testClassType(d)时,testClassType函数中的expression b具有静态类型Base和动态类型Derived。但是,如果Base中没有一个虚拟函数,typeid将始终报告静态类型- Base。一旦您使Base成为多态的,代码将报告b的动态类型,即Derived。
最重要的是,正如Oli在注释中正确指出的那样,type_info::name()方法的结果不能保证包含任何有意义的信息。它可以为所有类型返回相同的"Hello World"字符串。
发布于 2011-01-17 07:58:47
至少有一个虚拟成员函数的类称为多态类。
多态类的每个实例在运行时都(以某种方式)与用于实例化的原始类相关联。这是由typeid使用的。并且还用于虚拟成员函数的调用。
当您通过删除f使类成为非多态时,那么在testClassType中所知道的就是它是一个Base。不对类型进行运行时检查。
干杯&哈。
https://stackoverflow.com/questions/4708931
复制相似问题