Where there is a dream ,there is hope

  C++博客 :: 首页 :: 联系 :: 聚合  :: 管理
  64 Posts :: 0 Stories :: 8 Comments :: 0 Trackbacks

常用链接

留言簿(1)

我参与的团队

搜索

  •  

最新评论

阅读排行榜

评论排行榜

static关键字在C和C++中的用法稍有区别,主要是C++扩展了static关键字的作用
C 用法
1.修饰函数成员变量:例

//test.h
void test_static_var();

//test.c
void test_static_var()
{
    
static int var=0;//!不初始化默认为0
    var++;
    printf(
"static int var : %d \n", var);
}


//main.c
int main()
{
    
for (int i=0; i<10; i++)
    
{
        test_static_var();
    }

    getchar();
    
return 0;
}

2.在文件级别(即:在函数体外)修饰 变量或者函数,则表示该变量只在该文件中可见及可用
//test.h
void test_static_funtion_one();
void test_static_fuction_two();

//test.c
void test_static_funtion_one()
{
    printf(
"This is a normal function. \n");
}

static
void test_static_fuction_two()
{
    printf(
"This is a function modified by static. \n");
}


//main.c

int main()
{
    test_static_funtion_one();
    test_static_fuction_two();
    getchar();
    
return 0;
}

这样就会报错:LNK2001: 无法解析的外部符号 "void __cdecl test_static_fuction_two(void)" (?test_static_fuction_two@@YAXXZ)
原因就是test_static_fuction_two()被修饰为static ,如果main中不调用的话,编译可以通过(VS08),否则便以失败
修饰为static后,它只能在test.c中使用。

C++中包含了前两种方法,又扩展了下面两种方法:
3.修饰class 数据成员,称为 静态数据成员
4.修饰class 函数成员,称之为 静态成员函数
//test.h
     class TestA
     
{
     
public:
         
         
static int s_count;
         
static int getCount();
     
public:
         
int m_value;
     }
;

//test.c
    int TestA::s_count=0;
    
int TestA::getCount()
    
{
        
//m_value+=m_value; 静态函数中只能操作静态数据成员
        return s_count;
    }
因为静态成员函数没有传入隐式的this指针,所以,它不能使用. 、->操作符 ;不能是virtual 的,不能和非静态的同名
posted on 2011-02-16 12:21 IT菜鸟 阅读(191) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理