---- 整理自狄泰软件唐佐林老师课程
在面向对象中可能出现下面的情况:
这个时候就会出现问题:(由于 赋值兼容性原则 )没法通过一个父类指针判断指向的是父类对象还是子类对象


基类指针是否可以强制类型转换为子类指针取决于动态类型
C++中如何得到 动态类型 ?
#include
#include
using namespace std;
class Base
{
public:
virtual string type()
{
return "Base";
}
};
class Derived : public Base
{
public:
string type()
{
return "Derived";
}
void printf()
{
cout << "I'm a Derived." << endl;
}
};
class Child : public Base
{
public:
string type()
{
return "Child";
}
};
void test(Base* b)
{
/* 危险的转换方式 */
// Derived* d = static_cast(b);
if( b->type() == "Derived" )
{
Derived* d = static_cast<Derived*>(b);
d->printf();
}
// cout << dynamic_cast(b) << endl;
}
int main(int argc, char *argv[])
{
Base b;
Derived d;
Child c;
test(&b);
test(&d);
test(&c);
return 0;
}

向上/向下转换可参看 55 - 经典问题解析四(动态内存分配&虚函数&继承中的强制类型转换)
int i = 0;
const type_info& tiv = typeid(i);
const type_info& tii = typeid(int);
cout << (tiv == tii) << endl;
#include
#include
#include
using namespace std;
class Base
{
public:
virtual ~Base()
{
}
};
class Derived : public Base
{
public:
void printf()
{
cout << "I'm a Derived." << endl;
}
};
void test(Base* b)
{
const type_info& tb = typeid(*b);
cout << tb.name() << endl;
}
int main(int argc, char *argv[])
{
int i = 0;
const type_info& tiv = typeid(i);
const type_info& tii = typeid(int);
cout << (tiv == tii) << endl;
Base b;
Derived d;
test(&b);
test(&d);
return 0;
}

