static_cast,const_cast,dynamic_cast,reinterpret_cast的用法

來源:互聯網
上載者:User

下文轉自:

http://heavenguest.spaces.live.com/?_c11_BlogPart_BlogPart=blogview&_c=BlogPart&partqs=cat%3DQT

 

資料類型轉換:static_cast,const_cast等用法(轉載)
* C++提供了四種新的類型強制:

static_cast
const_cast
reinterpret_cast
dynamic_cast 1)staic_cast靜態強制; 不能在無關的指標之間進行static類型強制
class CAnimal
{
//...
public:
CAnimal(){}
}; class CGiraffe:public CAnimal
{
//...
public:
CGiraffe(){}
}; int main(void)
{
CAnimal an;
CGiraffe jean; an = static_cast<CAnimal>(jean);//將對象jean強製成CAnimal類型
return 0;
} 2、const_cast類型強制 const_cast類型強制將一個const變數變成一個非const的等價形式
int main()
{
const int j = 99;
int * k; k = const_cast<int *>(&j);//解除const
return 0;
} 3、reinterpret_cast運算子 reinterpret_cast運算子用來將一個類型指標轉變為另一種類型的指標,也用在將整開型量轉為指標,或將指標轉為整型量上;
int main()
{
int j = 10;
int * ptr = &j;
char * cptr; cptr = reinterpret_cast<char *>(ptr);//將int指標類型轉變為char的指標類型 return 0;
} 4、dynamic_cast運算子 dynamic_cast的主要目的是: 1)它返回衍生類別對象的地址;
2)它測試基類指標是否指向下一角括弧<>中所指定類型的對象 dynamic_cast是一個運行時類型資訊,dynamic_cast運算子將指向派生對象的基類部分的基類指標轉變為指向派生對象的衍生類別指標,dynamic_cast必須嚴格地指定與派生對象相同的類,或者它返回NULL指標;
class CAnimal
{
//...
};
class CGiraffe:public CAnimal
{
//...
};
class CGoat:public CAnimal
{
//...
}; int main()
{
CGiraffe gene;
CAnimal * aptr = &gene;
CGiraffe * ptr1,* ptr2; ptr1 = dynamic_cast<CGiraffe *>(aptr);
ptr2 = dynamic_cast<CGoat *>(aptr); //return NULL return 0;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.