#include <iostream>
using namespace std;
int main( void )
{
cout << "1111:"<<typeid(1.1f).name() << endl;
cout << "1111:"<<typeid(1).name() << endl;
cout << "1111:"<<typeid('c').name() << endl;
class Base1
{
};
class Derive1 : public Base1
{
};
Derive1 d1;
Base1& b1 = d1;
cout << "2222:"<< typeid(b1).name() << endl; // 輸出"class Base1",因為Derive1和Base1之間沒有多態性
// 編譯時間需要加參數 /GR
class Base2
{
virtual void fun( void ) {
}
};
class Derive2 : public Base2
{
};
Derive2 d2;
Base2& b2 = d2;
Base2 * p = &d2;
cout << "3333:"<< typeid(b2).name() << endl; // 輸出"class Derive2",因為Derive1和Base1之間有了多態性
class Derive22 : public Base2
{
};
// 指標強制轉化失敗後可以比較指標是否為零,而引用卻沒辦法,所以引用制轉化失敗後拋出異常
Derive2* pb1 = dynamic_cast<Derive2*>(p);
cout << "333_1:"<< boolalpha << (0!=pb1) << endl; // 輸出"true",因為b2本身就確實是Derive2
Derive22* pb2 = dynamic_cast<Derive22*>(p);
cout << "333_2:"<< boolalpha << (0!=pb2) << endl; // 輸出"false",因為b2本身不是Derive22
try {
Derive2& rb1 = dynamic_cast<Derive2&>(b2);
cout << "4444:"<< "true" << endl;
}
catch( bad_cast )
{
cout << "5555:"<< "false" << endl;
}
try {
Derive22& rb2 = dynamic_cast<Derive22&>(b2);
cout << "6666:"<< "true" << endl;
} catch( ... )
{
cout << "7777:"<< "false" << endl;
}
getchar();
return 0;
}