不能用類型不匹配的指針來完成賦值,如下代碼是錯的:
int i = 0;
double *dp = &i; // 非法,類型不匹配
但是 void* 可用于存放任意對象的地址:
int i = 42;
void *p = &i; // 合法
還有特殊字面值 nullptr,可以轉(zhuǎn)換成任意其它的指針類型,用來判斷指針是否指向了一個合法的對象。
如果一定要完成指針的類型轉(zhuǎn)換,可以使用 C++11 的幾種強(qiáng)制類型轉(zhuǎn)換:
- 指針類型轉(zhuǎn)換 (reinterpret_cast)
int *pint = 1;
char *pch = reinterpret_cast<char *>(pint);
- 涉及到 const 的指針類型轉(zhuǎn)換 (const_cast)
const int num[5] = { 1,2,3,4,5 };
const int *p = num;
int *pint = const_cast<int *>(p);
- 子類指針轉(zhuǎn)化為父類指針 (dynamic_cast)
class man {
public:
int name;
// 加上 virtual 關(guān)鍵字, 可以使得父類用子類初始化后可以調(diào)用子類的函數(shù)
virtual void run() {
cout << "man is running" << endl;
}
};
class son : public man {
public:
void run() {
cout << "son is running" << endl;
}
};
void main()
{
man *pman = new man;
son *pson = new son;
//子類指針轉(zhuǎn)換為父類指針, 但是還是調(diào)用子類的函數(shù)
man *pfu = dynamic_cast<man *>(pson);
pfu->run();
}