static功能介绍

static作用主要有以下四点:

1、修饰普通变量,变量存储在静态区,只会被初始化一次,默认值为0;

2、修饰普通函数,表明函数的作用范围,仅在定义该函数的文件内才能使用。在多人开发项目时,为了防止与他人命名空间里的函数重名,可以将函数定为 static。

3、修饰成员变量,该类只保存一个该变量,可以通过类直接访问,在类中声明,在类外初始化。

4、修饰成员函数,无需生成对象可以直接访问,static函数内不能访问非静态成员。

备注:类在实例化的时候,是通过new关键字来进行的,new时会默认提供一个隐藏的this指针,该指针的作用是用来访问实例对象的成员变量的。

 

第一点:

demo:

#include <iostream>
using namespace std;
void fun()
{
    static int a = 10;
    a++;
    cout<<a<<endl;
}
int main()
{
    for(int i = 0; i < 5; i++)
    {
        fun();
    }
    return 0;
}

结果:

11

12

13

14

15

可以看到,a定义完之后,a是存储在静态区,不会随着fun函数的退出而消亡,它的值也会随着操作的改变而改变。

第二点:

demo:

static_test.h
#include <iostream>
void fun1();
static void fun2();
//void fun2();
static_test.cpp
#include <iostream>
#include "static_test.h"
using namespace std;
void fun1()
{
    cout<<"fun1()"<<endl;
}
static void fun2()
{
    cout<<"fun2()"<<endl;
}
/*
void fun2()
{
    cout<<"fun2()"<<endl;
}
*/
static_test_2.cpp
#include <iostream>
#include "static_test.h"

int main()
{
    fun1();
    fun2();
    return 0;
}

这个时候g++ -o static_test static_test_2.cpp static_test.cpp编译是会报错的,找不到

static_test_2.cpp:(.text+0xa): undefined reference to `fun2()' fun2()函数,因为fun2为静态函数,只能被定义的源文件访问,这样就避免了函数重名的情况。

第三种:

demo:

#include <iostream>
using namespace std;
class Static_test
{
public:
    static int a;
    int b;
    void fun()
    {
        cout<<a<<endl;
    }
};
int Static_test::a = 10;
int main()
{
    Static_test A;
    A.fun();
    cout<<Static_test::a<<endl;
    //Static_test::fun();
    return 0;
}

结果:

10

10

静态成员变量不要在头文件中初始化,这样做会重复定义。在类中声明,在类外初始化。可以通过类名直接访问,所有的类对象共用同一个该静态成员变量。

第四种:

#include <iostream>
using namespace std;
class Static_test
{
public:
    static int a;
    int b;
    static void fun()
    {
        cout<<a<<endl;
        //cout<<b<<endl;
    }
};
int Static_test::a = 10;
int main()
{
    Static_test::fun();
    return 0;
}

结果:

10

静态成员函数可直接被类访问,静态成员函数只能访问静态成员变量。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值