C/C++ static µÄ×÷ÓÃ
ת×Ô£ºhttp://blog.csdn.net/xiaocai0001/archive/2006/04/14/662921.aspx
static¹Ø¼ü×ÖÊÇC, C++Öж¼´æÔڵĹؼü×Ö, ËüÖ÷ÒªÓÐÈýÖÖʹÓ÷½Ê½, ÆäÖÐÇ°Á½ÖÖÔÚC/C++ÓïÑÔÖÐʹÓÃ, µÚÈýÖÖÖ»ÔÚC++ÖÐʹÓÃ(C,C++ÖоßÌåϸ΢²Ù×÷²»¾¡Ïàͬ, ±¾ÎÄÒÔC++Ϊ׼).
(1)¾Ö²¿¾²Ì¬±äÁ¿
(2)Íⲿ¾²Ì¬±äÁ¿/º¯Êý
(3)¾²Ì¬Êý¾Ý³ÉÔ±/³ÉÔ±º¯Êý
ÏÂÃæ¾ÍÕâÈýÖÖʹÓ÷½Ê½¼°×¢ÒâÊÂÏî·Ö±ð˵Ã÷
Ò»¡¢¾Ö²¿¾²Ì¬±äÁ¿
ÔÚC/C++ÖÐ, ¾Ö²¿±äÁ¿°´ÕÕ´æ´¢ÐÎʽ¿É·ÖΪÈýÖÖauto, static, register
(<CÓïÑÔ³ÌÐòÉè¼Æ(µÚ¶þ°æ)>Ì·ºÆÇ¿, µÚ174-175Ò³)
ÓëautoÀàÐÍ(ÆÕͨ)¾Ö²¿±äÁ¿Ïà±È, static¾Ö²¿±äÁ¿ÓÐÈýµã²»Í¬
1. ´æ´¢¿Õ¼ä·ÖÅ䲻ͬ
autoÀàÐÍ·ÖÅäÔÚÕ»ÉÏ, ÊôÓÚ¶¯Ì¬´æ´¢Àà±ð, Õ¼¶¯Ì¬´æ´¢Çø¿Õ¼ä, º¯Êýµ÷ÓýáÊøºó×Ô¶¯ÊÍ·Å, ¶østatic·ÖÅäÔÚ¾²Ì¬´æ´¢Çø, ÔÚ³ÌÐòÕû¸öÔËÐÐÆڼ䶼²»ÊÍ·Å. Á½ÕßÖ®¼äµÄ×÷ÓÃÓòÏàͬ, µ«Éú´æÆÚ²»Í¬.
2. static¾Ö²¿±äÁ¿ÔÚËù´¦Ä£¿éÔÚ³õ´ÎÔËÐÐʱ½øÐгõʼ»¯¹¤×÷, ÇÒÖ»²Ù×÷Ò»´Î
3. ¶ÔÓÚ¾Ö²¿¾²Ì¬±äÁ¿, Èç¹û²»¸³³õÖµ, ±àÒëÆÚ»á×Ô¶¯¸³³õÖµ0»ò¿Õ×Ö·û, ¶øautoÀàÐ͵ijõÖµÊDz»È·¶¨µÄ. (¶ÔÓÚC++ÖеÄclass¶ÔÏóÀýÍâ, classµÄ¶ÔÏóʵÀýÈç¹û²»³õʼ»¯, Ôò»á×Ô¶¯µ÷ÓÃĬÈϹ¹Ô캯Êý, ²»¹ÜÊÇ·ñÊÇstaticÀàÐÍ)
Ìصã: static¾Ö²¿±äÁ¿µÄ”¼ÇÒäÐÔ”ÓëÉú´æÆڵĔȫ¾ÖÐÔ”
Ëùν”¼ÇÒäÐÔ”ÊÇÖ¸ÔÚÁ½´Îº¯Êýµ÷ÓÃʱ, ÔÚµÚ¶þ´Îµ÷ÓýøÈëʱ, Äܱ£³ÖµÚÒ»´Îµ÷ÓÃÍ˳öʱµÄÖµ.
ʾÀý³ÌÐòÒ»
#include <iostream>
using namespace std;
void staticLocalVar()
{
static int a = 0; // ÔËÐÐÆÚʱ³õʼ»¯Ò»´Î, Ï´ÎÔÙµ÷ÓÃʱ, ²»½øÐгõʼ»¯¹¤×÷
cout<<"a="<<a<<endl;
++a;
}
int main()
{
staticLocalVar(); // µÚÒ»´Îµ÷ÓÃ, Êä³öa=0
staticLocalVar(); // µÚ¶þ´Îµ÷ÓÃ, ¼ÇÒäÁ˵ÚÒ»´ÎÍ˳öʱµÄÖµ, Êä³öa=1
return 0;
}
Ó¦ÓÃ:
ÀûÓÔ¼ÇÒäÐÔ”, ¼Ç¼º¯Êýµ÷ÓõĴÎÊý(ʾÀý³ÌÐòÒ»)
ÀûÓÃÉú´æÆڵĔȫ¾ÖÐÔ”, ¸ÄÉÆ”return a pointer / reference to a local object”µÄÎÊÌâ. Local objectµÄÎÊÌâÔÚÓÚÍ˳öº¯Êý, Éú´æÆÚ¼´½áÊø,. ÀûÓÃstaticµÄ×÷ÓÃ, ÑÓ³¤±äÁ¿µÄÉú´æÆÚ.
ʾÀý³ÌÐò¶þ:
// IP address to string format
// Used in Ethernet Frame and IP Header analysis
const char * IpToStr(UINT32 IpAddr)
{
static char strBuff[16]; // static¾Ö²¿±äÁ¿, ÓÃÓÚ·µ»Øµ
Ïà¹ØÎĵµ£º
#include <stdio.h>
int Count=0;
void move(char x,int n,char z){
printf(" %d. disk %d: %c => %c\n",++Count,n,x,z);
}//move
// ½«Ëþ×ùxÉÏ°´Ö±¾¶ÓÉСµ½´óÇÒ×ÔÉ϶øϱàºÅΪ1ÖÁnµÄn¸öÔ²ÅÌ°´¹æÔò°áµ½Ëþ×ùzÉÏ£¬y¿ÉÓÃ×÷¸¨ÖúËþ×ù
void Hanoi(int n,char x,char y,char z){
if (n==1) move(x,1,z ......
//ÊäÈë²ÎÊý£º*str ËÑË÷×Ö·û´®
// subStrLen ÓÃÓÚ·µ»ØÕÒµ½µÄ×î´ó×Ó×Ö·û´®³¤¶È
//·µ»Ø£ºÕÒµ½µÄ×î´ó×Ó×Ö·û´®Ö¸Õë
char * findMaxSubStr(char *str, int &subStrLen){
char *subStr;
char *p = str;
int index[256] ;
for (int ix = 0; ix < sizeof(index)/sizeof(index[0]); ix++)
{
in ......
¡¾1¡¿ “ = ”µÄÓÅÏȼ¶µÍÓÚ “ || ” ÇÒ “ = ” ΪÓÒ½áºÏÐÔ£¬×¢ÒâһϴúÂëΪËÀÑ»·£ºwhile(c=' '||c=='\t'||c=='\n')
³ÌÐò±¾ÒâÊÇÌø¹ý¿Õ¸ñ£¬ÖƱí·û£¬»»Ðзû£¬µ«ÓÉÓÚ²»Ð¡ÐĽ«c==' 'д³ÉÁËc= ' 'µ¼Ö³ÌÐò½øÈëËÀÑ»·
¡¾2¡¿a=-1 ÔÚºÜÀϵÄC°æ±¾ÀïÀí½âΪ a =- 1
¡¾3 ......
PART (1)
/*
===============================================
¾µäÅÅÐò˼Ï룬²¢ÓÃCÓïÑÔÖ¸ÕëʵÏÖÅÅÐòËã·¨
================================================
*/
/*
=============================================================================
Ïà¹Ø֪ʶ½éÉÜ£¨ËùÓж¨ÒåֻΪ°ïÖú¶ÁÕßÀí½âÏà¹Ø¸ÅÄ²¢·ÇÑϸñ¶¨ ......