为了我自己的理解,我已经实现了以下程序。但是我看到 typeid 返回的类名略有修改。我知道这可能是因为名称修改,但包括 extern C 也无济于事。
有人可以帮我理解为什么会出现这种行为以及如何解决吗?
g++ 版本 - 4.7.0
#include <iostream>
#include <typeinfo>
using namespace std;
class Base
{
public:
virtual ~Base(){}
};
class Derive : public Base
{
public:
~Derive(){}
};
class newBase
{
public:
~newBase(){}
};
class newDerive : public newBase
{
public:
~newDerive(){}
};
int main()
{
Base base;
Derive derive;
Base *pBase;
Base & rBase1 = base;
Base & rBase2 = derive;
newBase newbase;
newDerive newderive;
newBase *pNewBase;
//Results with polymorphic class.
pBase = &base;
cout<<"Base class pointer pBase contains object of type "<<typeid(*pBase).name() <<".\n";
pBase = &derive;
cout<<"Base class pointer pBase contains object of type "<<typeid(*pBase).name()<<".\n";
cout<<"\nReference variable rBase1 referring to "<<typeid(rBase1).name()<<".\n";
cout<<"Reference variable rBase2 referring to "<<typeid(rBase2).name()<<".\n";
//Results with non-polymorphic class.
pNewBase = &newbase;
cout<<"\nBase class pointer pNewBase contains object of type "<<typeid(*pNewBase).name()<<".\n";
pNewBase = &newderive;
cout<<"Base class pointer pNewBase contains object of type "<<typeid(*pNewBase).name()<<".\n";
return 0;
}
Output -
Base class pointer pBase contains object of type 4Base.
Base class pointer pBase contains object of type 6Derive.
Reference variable rBase1 referring to 4Base.
Reference variable rBase2 referring to 6Derive.
Base class pointer pNewBase contains object of type 7newBase.
Base class pointer pNewBase contains object of type 7newBase.
我期待程序中指定的类名。
非常感谢。