c/c++Ç¿ÖÆÀàÐÍת»»
Q:ʲôÊÇC·ç¸ñת»»£¿Ê²Ã´ÊÇstatic_cast, dynamic_cast ÒÔ¼° reinterpret_cast£¿Çø±ðÊÇʲô£¿ÎªÊ²Ã´Òª×¢Ò⣿
A:ת»»µÄº¬ÒåÊÇͨ¹ý¸Ä±äÒ»¸ö±äÁ¿µÄÀàÐÍΪ±ðµÄÀàÐÍ´Ó¶ø¸Ä±ä¸Ã±äÁ¿µÄ±íʾ·½Ê½¡£ÎªÁËÀàÐÍת»»Ò»¸ö¼òµ¥¶ÔÏóΪÁíÒ»¸ö¶ÔÏóÄã»áʹÓô«Í³µÄÀàÐÍת»»²Ù×÷·û¡£±ÈÈ磬ΪÁËת»»Ò»¸öÀàÐÍΪdouboleµÄ¸¡µãÊýµÄÖ¸Õëµ½ÕûÐÍ£º
´úÂë:
int i;
double d;
i = (int) d;
»òÕߣº
i = int (d);
¶ÔÓÚ¾ßÓбê×¼¶¨Òåת»»µÄ¼òµ¥ÀàÐͶøÑÔ¹¤×÷µÄºÜºÃ¡£È»¶ø£¬ÕâÑùµÄת»»·ûÒ²Äܲ»·ÖÔí°×µÄÓ¦ÓÃÓÚÀࣨclass£©ºÍÀàµÄÖ¸Õë¡£ANSI-C++±ê×¼¶¨ÒåÁËËĸöеÄת»»·û£º'reinterpret_cast', 'static_cast', 'dynamic_cast' ºÍ 'const_cast'£¬Ä¿µÄÔÚÓÚ¿ØÖÆÀà(class)Ö®¼äµÄÀàÐÍת»»¡£
´úÂë:
reinterpret_cast<new_type>(expression)
dynamic_cast<new_type>(expression)
static_cast<new_type>(expression)
const_cast<new_type>(expression)
1 reinterpret_cast
'reinterpret_cast'ת»»Ò»¸öÖ¸ÕëΪÆäËüÀàÐ͵ÄÖ¸Õë¡£ËüÒ²ÔÊÐí´ÓÒ»¸öÖ¸Õëת»»ÎªÕûÊýÀàÐÍ¡£·´Ö®ÒàÈ»¡££¨Òë×¢£ºÊÇÖ¸Õë¾ßÌåµÄµØÖ·Öµ×÷ΪÕûÊýÖµ£¿£©
Õâ¸ö²Ù×÷·ûÄܹ»ÔÚ·ÇÏà¹ØµÄÀàÐÍÖ®¼äת»»¡£²Ù×÷½á¹ûÖ»ÊǼòµ¥µÄ´ÓÒ»¸öÖ¸Õëµ½±ðµÄÖ¸ÕëµÄÖµµÄ¶þ½øÖÆ¿½±´¡£ÔÚÀàÐÍÖ®¼äÖ¸ÏòµÄÄÚÈݲ»×öÈκÎÀàÐ͵ļì²éºÍת»»¡£
Èç¹ûÇé¿öÊÇ´ÓÒ»¸öÖ¸Õëµ½ÕûÐ͵Ŀ½±´£¬ÄÚÈݵĽâÊÍÊÇϵͳÏà¹ØµÄ£¬ËùÒÔÈκεÄʵÏÖ¶¼²»ÊÇ·½±ãµÄ¡£Ò»¸öת»»µ½×ã¹»´óµÄÕûÐÍÄܹ»°üº¬ËüµÄÖ¸ÕëÊÇÄܹ»×ª»»»ØÓÐЧµÄÖ¸ÕëµÄ¡£
´úÂë:
class A {};
class B {};
A * a = new A;
B * b = reinterpret_cast<B *>(a);
'reinterpret_cast'¾ÍÏñ´«Í³µÄÀàÐÍת»»Ò»Ñù¶Ô´ýËùÓÐÖ¸ÕëµÄÀàÐÍת»»¡£
2 static_cast
'static_cast'ÔÊÐíÖ´ÐÐÈÎÒâµÄÒþʽת»»ºÍÏ෴ת»»¶¯×÷¡££¨¼´Ê¹ËüÊDz»ÔÊÐíÒþʽµÄ£©
Ó¦Óõ½ÀàµÄÖ¸ÕëÉÏ£¬Òâ˼ÊÇ˵ËüÔÊÐí×ÓÀàÀàÐ͵ÄÖ¸Õëת»»Îª¸¸ÀàÀàÐ͵ÄÖ¸Õ루ÕâÊÇÒ»¸öÓÐЧµÄÒþʽת»»£©£¬Í¬Ê±£¬Ò²Äܹ»Ö´ÐÐÏà·´¶¯×÷£º×ª»»¸¸ÀàΪËüµÄ×ÓÀà¡£
ÔÚÕâ×îºóÀý×ÓÀ±»×ª»»µÄ¸¸ÀàûÓб»¼ì²éÊÇ·ñÓëÄ¿µÄÀàÐÍÏàÒ»Ö¡£
´úÂ룺
class Base {};
class Derived : public Base {};
Base *a = new Base;
Derived *b = static_cast<Derived *>(a);
'static_cast'³ýÁ˲Ù×÷ÀàÐÍÖ¸Õ룬ҲÄÜÓÃÓÚÖ´ÐÐÀàÐͶ¨ÒåµÄÏÔʽµÄת»»£¬ÒÔ¼°»ù´¡ÀàÐÍÖ®¼äµÄ±ê׼ת»»:
´úÂë:
double d = 3.14159265;
int i = static_c
Ïà¹ØÎĵµ£º
ϵͳ»·¾³£ºWindows 7
Èí¼þ»·¾³£ºVisual C++ 2008 SP1 +SQL Server 2005
±¾´ÎÄ¿µÄ£º±àдһ¸öº½¿Õ¹ÜÀíϵͳ
ÕâÊÇÊý¾Ý¿â¿Î³ÌÉè¼ÆµÄ³É¹û£¬ËäÈ»³É¼¨²»¼Ñ£¬µ«ÊÇ×÷ΪÎÒÓÃVC++ ÒÔÀ´±àдµÄ×î´ó³ÌÐò»¹ÊÇ´«µ½ÍøÉÏ£¬ÒÔ¹©²Î¿¼¡£ÓÃVC++ ×öÊý¾Ý¿âÉè¼Æ²¢²»ÈÝÒ×£¬µ«Ò²²»ÊDz»¿ÉÄÜ¡£ÒÔÏÂÊÇÎҵijÌÐò½çÃ棬ºóÃæ ......
ÒýÑÔ
¡¡¡¡Ö¸ÕëÊÇC/C++ÓïÑÔµÄÌØÉ«£¬¶øÊý×éÃûÓëÖ¸ÕëÓÐÌ«¶àµÄÏàËÆ£¬ÉõÖÁºÜ¶àʱºò£¬Êý×éÃû¿ÉÒÔ×÷ΪָÕëʹÓá£ÓÚÊǺõ£¬ºÜ¶à³ÌÐòÉè¼ÆÕ߾ͱ»¸ãºýÍ¿ÁË¡£¶øÐí¶àµÄ´óѧÀÏʦ£¬ËûÃÇÔÚCÓïÑԵĽÌѧ¹ý³ÌÖÐÒ²´íÎóµÃ¸øѧÉú½²½â£º"Êý×éÃû¾ÍÊÇÖ¸Õë"¡£ºÜÐÒÔË£¬ÎҵĴóѧÀÏʦ¾ÍÊÇÆäÖÐÖ®Ò»¡£Ê±ÖÁ½ñÈÕ£¬ÎÒÈÕ¸´Ò»ÈյؽøÐÐ×ÅC/C++ÏîÄ¿µÄ¿ª·¢£¬¶øÉí±ß» ......
µÚÒ»Õ ¸ÅÄî
Ö¸ÕëÊÇÒ»¸öÌØÊâµÄ±äÁ¿£¬ËüÀïÃæ´æ´¢µÄÊýÖµ±»½âÊͳÉΪÄÚ´æÀïµÄÒ»¸öµØÖ·¡£Òª¸ãÇåÒ»¸öÖ¸ÕëÐèÒª¸ãÇåÖ¸ÕëµÄËÄ·½ÃæµÄÄÚÈÝ£ºÖ¸ÕëµÄÀàÐÍ£¬Ö¸ÕëËùÖ¸ÏòµÄÀàÐÍ£¬Ö¸ÕëµÄÖµ»òÕß½ÐÖ¸ÕëËùÖ¸ÏòµÄÄÚ´æÇø£¬»¹ÓÐÖ¸Õë±¾ÉíËùÕ¼¾ÝµÄÄÚ´æÇø¡£ÈÃÎÒÃÇ·Ö±ð˵Ã÷¡£
ÏÈÉùÃ÷¼¸¸öÖ¸Õë·Å×Å×öÀý×Ó£º
ÀýÒ»£º
(1)int *ptr;
(2)char ......