cÓëc++ staticº¯ÊýµÄÇø±ð
cÓëc++ staticº¯ÊýµÄÇø±ð
c
Óëc++ static
º¯ÊýµÄÇø±ð
static
¹Ø¼ü×ÖÊÇ
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
µÄÎÊÌâÔÚÓÚÍ˳öº¯Êý
,
Éú´æÆÚ¼´½áÊø
,.
À
Ïà¹ØÎĵµ£º
Ô´Âë:
# include <stdio.h>
int main()
{
int num;
/* ÏÂÃ涨ÒåµÄ¸÷±äÁ¿£¬·Ö±ð´ú±í¸öλ£¬Ê®Î»£¬°Ùλ£¬Ç§Î»£¬Íòλ£¬Ê®ÍòλÒÔ¼°Î»Êý */
int indiv, ten, hundred, thousand;
int ten_thousand, hundred_thous ......
Ô´Âë:
# include <stdio.h>
int main()
{
int x, y, num1, num2, temp;
printf("ÇëÊäÈëÁ½¸öÕýÕûÊý£º\n");
scanf("%d %d", &num1, &num2);
if(num1 < num2)
......
Ô´Â룺
/* ʹÓÃÑ¡Ôñ·¨ÅÅÐò */
# include <stdio.h>
int main()
{
int i, j, min, temp;
/* ¶¨ÒåÒ»¸öÕûÐ͵ÄһάÊý×é */
int array[10];
/* ÊäÈëÊý¾Ý */
printf("Please input ten integ ......
Ô´Â룺
# include <stdio.h>
/* ºê¶¨Òå */
# define MAX 100
# define LEN 80
/* Ò»¸ö·Ç³£¼òµ¥µÄÎı¾±à¼Æ÷ */
int main()
{
char text[MAX][LEN]; // ¶¨Òå×Ö·ûÐÍÊý×é
register int t, i, j; /* ¶¨ÒåÈý¸ö¼Ä´æÆ÷±äÁ¿ */
  ......