範例
#include
<typeinfo>
class
Shape{
public
:
virtual
~Shape()=0;
};
class
Circle :
public
Shape{};
class
Square :
public
Shape{};
void
function(
const
Shape * s)
{
if
(
typeid
(*s)==
typeid
(Circle))
{
//對 Circle 執行一些動作
}
else if
(
typeid
(*s)==
typeid
(Square))
{
//對 Square 執行一些動作
}
}
解決方案
利用傳回唯一 ID 的虛擬 classOf() 函數來實作類別,或測試動態強制轉型是否成功。
class
Shape{
public
:
virtual
~Shape()=0;
};
class
Circle :
public
Shape{};
class
Square :
public
Shape{};
void
function(
const
Shape * s)
{
Shape *sh =
const_cast
<Shape*> (s);
if
(
dynamic_cast
<Circle *>(sh)
)
{
//對 Circle 執行一些動作
}
else if
(
dynamic_cast
<Square *>(sh)
)
{
//對 Square 執行一些動作
}
}