C/C++ÖÐStaticµÄ×÷ÓÃÏêÊö
C/C++ÖÐStaticµÄ×÷ÓÃÏêÊö
http://developer.51cto.com 2008-12-29 09:52 ØýÃû ÖйúITʵÑéÊÒ ÎÒÒªÆÀÂÛ(0)
CÓïÑÔÖУ¬staticµÄ×ÖÃæÒâ˼ºÜÈÝÒ×°ÑÎÒÃǵ¼ÈëÆç;¡£±¾ÎĽ«¶ÔC/C++ÖÐStatic½øÐÐÏêÊö¡£
1.ÏÈÀ´½éÉÜËüµÄµÚÒ»ÌõÒ²ÊÇ×îÖØÒªµÄÒ»Ìõ£ºÒþ²Ø¡£
µ±ÎÒÃÇͬʱ±àÒë¶à¸öÎļþʱ£¬ËùÓÐδ¼Óstaticǰ׺µÄÈ«¾Ö±äÁ¿ºÍº¯Êý¶¼¾ßÓÐÈ«¾Ö¿É¼ûÐÔ¡£ÎªÀí½âÕâ¾ä»°£¬ÎÒ¾ÙÀýÀ´ËµÃ÷¡£ÎÒÃÇҪͬʱ±àÒëÁ½¸öÔ´Îļþ£¬Ò»¸öÊÇa.c£¬ÁíÒ»¸öÊÇmain.c.
ÏÂÃæÊÇa.cµÄÄÚÈÝ£º
char a = 'A'; // global variable
void msg()
{
printf("Hello\n");
}
ÏÂÃæÊÇmain.cµÄÄÚÈÝ£º
int main(void)
{
extern char a; // extern variable must be declared before use
printf("%c ", a);
(void)msg();
return 0;
}
³ÌÐòµÄÔËÐнá¹ûÊÇ£º
A Hello
Äã¿ÉÄÜ»áÎÊ£ºÎªÊ²Ã´ÔÚa.cÖж¨ÒåµÄÈ«¾Ö±äÁ¿aºÍº¯ÊýmsgÄÜÔÚmain.cÖÐʹÓã¿Ç°Ãæ˵¹ý£¬ËùÓÐδ¼Óstaticǰ׺µÄÈ«¾Ö±äÁ¿ºÍº¯Êý¶¼¾ßÓÐÈ«¾Ö¿É¼ûÐÔ£¬ÆäËüµÄÔ´ÎļþÒ²ÄÜ·ÃÎÊ¡£´ËÀýÖУ¬aÊÇÈ«¾Ö±äÁ¿£¬msgÊǺ¯Êý£¬²¢ÇÒ¶¼Ã»ÓмÓstaticǰ׺£¬Òò´Ë¶ÔÓÚÁíÍâµÄÔ´Îļþmain.cÊǿɼûµÄ¡£
Èç¹û¼ÓÁËstatic£¬¾Í»á¶ÔÆäËüÔ´ÎļþÒþ²Ø¡£ÀýÈçÔÚaºÍmsgµÄ¶¨ÒåÇ°¼ÓÉÏstatic£¬main.c¾Í¿´²»µ½ËüÃÇÁË¡£ÀûÓÃÕâÒ»ÌØÐÔ¿ÉÒÔÔÚ²»Í¬µÄÎļþÖж¨ÒåͬÃûº¯ÊýºÍͬÃû±äÁ¿£¬¶ø²»±Øµ£ÐÄÃüÃû³åÍ»¡£Static¿ÉÒÔÓÃ×÷º¯ÊýºÍ±äÁ¿µÄǰ׺£¬¶ÔÓÚº¯ÊýÀ´½²£¬staticµÄ×÷ÓýöÏÞÓÚÒþ²Ø£¬¶ø¶ÔÓÚ±äÁ¿£¬static»¹ÓÐÏÂÃæÁ½¸ö×÷Óá£
2.staticµÄµÚ¶þ¸ö×÷ÓÃÊDZ£³Ö±äÁ¿ÄÚÈݵij־á£
´æ´¢ÔÚ¾²Ì¬Êý¾ÝÇøµÄ±äÁ¿»áÔÚ³ÌÐò¸Õ¿ªÊ¼ÔËÐÐʱ¾ÍÍê³É³õʼ»¯£¬Ò²ÊÇΨһµÄÒ»´Î³õʼ»¯¡£¹²ÓÐÁ½ÖÖ±äÁ¿´æ´¢ÔÚ¾²Ì¬´æ´¢Çø£ºÈ«¾Ö±äÁ¿ºÍstatic±äÁ¿£¬Ö»²»¹ýºÍÈ«¾Ö±äÁ¿±ÈÆðÀ´£¬static¿ÉÒÔ¿ØÖƱäÁ¿µÄ¿É¼û·¶Î§£¬Ëµµ½µ×static»¹ÊÇÓÃÀ´Òþ²ØµÄ¡£ËäÈ»ÕâÖÖÓ÷¨²»³£¼û£¬µ«ÎÒ»¹ÊǾÙÒ»¸öÀý×Ó¡£
#include £¼stdio.h£¾
int fun(void){
static int count = 10; // ÊÂʵÉϴ˸³ÖµÓï¾ä´ÓÀ´Ã»ÓÐÖ´Ðйý
return count--;
}
int count = 1;
int main(void)
{
printf("global\t\tlocal static\n");
for(; count £¼= 10; ++count)
printf("%d\t\t%d\n", count, fun());
return 0;
}
³ÌÐòµÄÔËÐнá¹ûÊÇ£º
global local static
1 10
2 9
3 8
4 7
5 6
6 5
7 4
8 3
9 2
10 1
3.staticµÄµÚÈý¸ö×÷ÓÃÊ
Ïà¹ØÎĵµ£º
2.2 ½â¾ö¿É²âÐÔÎÊÌâ
ÉÏÒ»½Ú¾ßÌå·ÖÎöÁ˿ɲâÐÔÎÊÌ⣬½ÓÏÂÀ´£¬ÎÒÃÇÀ´¿´¿´ÈçºÎ½â¾öÕâЩÎÊÌâ¡£ÏÂͼÖУ¬²ÊÉ«µÄ²¿·ÖÊÇÐèÒª½â¾öµÄ¿É²âÐԵľßÌåµÄÎÊÌâ¡£
ÓëÆäËû´úÂë¸ôÀë
ΪÁËÌá¸ßЧÂÊ£¬Ó¦¸ÃÒ»´ÎÐÔ½«Ò»Î»¹¤³Ìʦ¸ºÔðµÄ²âÊÔÈÎÎñ¸ôÀë³öÀ´¡£¸ôÀëʱ£¬Ó¦°ÑÔ´Îļþ·ÖΪÈýÀࣺ± ......
ʵÑéÒªÇó£º
1.±àд»ùÓÚTCPÐÒéµÄͨÐųÌÐò£¬°üÀ¨ServerÓëClientÁ½¸ö²¿·Ö¡£ÊµÏÖ»ØÉù³ÌÐò£º¼´¿Í»§¶Ë·¢ËÍÏûÏ¢£¬·þÎñÆ÷¶Ë½«ÊÕµ½µÄÏûÏ¢ÔÑù»áË͸ø¿Í»§¶Ë¡£
2.ÔÚµ¥»úÉÏÔËÐÐËüÃÇ£¬ÑéÖ¤ÆäͨÐŽá¹û£»
3.ÔÚ¶à»úÉÏÔËÐÐËüÃÇ£¬ÑéÖ¤ÆäͨÐŽá¹û£»£¨ChatServerÖ»ÐèÔËÐÐÔÚһ̨Ö÷»úÉÏ£¬ChatClient¿ÉÔÚÆäËüÖ÷»úÉÏÔËÐУ¨ÒªÖªµÀChatServerËùÔ ......
#include<stdio.h>
int cubeByValue(int n);
int main(){
int number = 5 ;
printf("The original value of number is %d\n",number);
number = cubeByValue(number);
printf("The new  ......
³£¼ûµÄÄÚ´æ·ÖÅäºÍʹÓôíÎó
1) ÄÚ´æµÄÉêÇëºÍ·ÖÅ䲢ûÓгɹ¦£¬µ«³ÌÐòԱȴʹÓÃÁËËü¡£Ò»Ð©ÐÂÊÖ¾³£»á·¸ÕâÖÖ´íÎó£¬ËûÃDz¢²»»áÁôÒâµ½ÄÚ´æûÓзÖÅä³É¹¦¡£ÅжÏÖ¸ÕëµÄÖµÊÇ·ñΪNULL¿ÉÒÔÓÐЧµØ±ÜÃâÕâÖÖ´íÎó¡£
2) ÄÚ´æµÄ·ÖÅäÒѾ³É¹¦£¬µ«ÊÇȴûÓнøÐгõʼ»¯¾ÍÖ±½ÓʹÓÃËüÁË¡£Ê×ÏÈÊ ......