我有一些 typeid 不打印运行时对象类型的代码。代码示例是:
class interface
{
public:
virtual void hello()
{
cout << "Hello interface: " << typeid(interface).name() << endl;
}
virtual ~interface() {}
};
class t1 : public interface
{
public:
virtual void hello ()
{
cout << "Hello t1: " << typeid(t1).name() << endl;
}
};
class t2 : public t1
{
public:
void hello ()
{
cout << "Hello t2: " << typeid(t2).name() << endl;
}
};
......
interface *p;
t1 *p1;
t2 *p2, *pt2;
t3 *p3, *pt3;
pt2 = new t2;
std::cout << "type1: " << abi::__cxa_demangle(typeid(pt2).name(), 0, 0, &status) << "\n\n";
p = pt2;
assert(p != NULL);
p->hello();
std::cout << "type2: " << abi::__cxa_demangle(typeid(p).name(), 0, 0, &status) << "\n\n";
p1 = dynamic_cast<t1 *>(p);
assert(p1 != NULL);
p1->hello();
std::cout << "type3: " << abi::__cxa_demangle(typeid(p1).name(), 0, 0, &status) << "\n\n";
p2 = dynamic_cast<t2 *>(p);
assert(p2 != NULL);
p2->hello();
std::cout << "type4: " << abi::__cxa_demangle(typeid(p2).name(), 0, 0, &status) << "\n\n";
我用“g++ -g -o ...”构建程序。然后输出是:
类型1:t2*
你好 t2: 2t2
type2: 接口*你好 t2: 2t2
type3: t1*你好 t2: 2t2
type4: t2*
打印输出似乎正确。但我希望 type2对于 RTTI也是t2* 。但是,输出是interface*。我希望 type3 也是t2*。哪里不对了?