2018-01-23

Static关键字用法

C语言中面向过程

  • 静态全局变量
//Example 1
#Include
using namespace std;
static int n;
int main()
{
    n = 20
}

静态全局变量的作用:
1.静态全局变量的作用域:不能被其他文件所引用,全局变量默认作用域是整个工程,一个文件中定义,另一个文件中extern声明,就可以使用了
2.其他文件中可以定义相同的变量名,而不冲突

  • 计算机内存分配原则
    对于一个完整的程序,在内存区中分布情况如下:
    代码区 //low address 全局数据区 堆区 栈区 //high address
    一般程序会把新的动态数据放在堆区,函数内部的自动变量放在栈区,函数退出时,会释放相应的空间,而静态数据(包括函数内部的静态局部变量)会放在全局数据区,并不会随着函数的退出而释放空间

  • 静态局部变量
#include
using namespace std;
int main()
{
    static int n = 10;
}

静态局部变量的作用:

  1. 通常,在函数体内定义了一个变量,每当这个函数运行到改语句的时候,会为该变量分配一个栈内存,函数退出时候,系统会收回栈内存,局部变量失效,
  2. 当该 变量用静态局部变量声明后,只会初始化一次,并且保存在全局数据区,每次的值会保存到下一次调用
C++语言中面向对象(类中的static关键字)
  • 静态数据成员
#include
using namespace std;
class Myclass
{
    public:
              Myclass(int a, int b, int c);
              void GetSum();
    private:
              int a, b, c;
              static int Sum;
}
int Myclass::Sum = 0;
Myclass::Myclass(int a, int b, int c)
{
    this - >a = a;
    this - >b = b;
    this - >c = c;
    Sum = a + b + c
}
Myclass::GetSum()
{
    
}

静态数据成员有以下特点:

  1. 对于非静态数据成员,每个类对象都会有一份拷贝,而静态数据成员,无论类对象被定义了多少个,静态数据成员在程序中也只有一份拷贝,只分配一次内存,由该类型的所有对象共享
  • 静态成员函数
#include
using namespace std;
class Myclass
{
        public:
            Myclass(int a, int b, int c);
            static void Getsum(); //声明静态成员函数
        private:
            int a, b, c;
            static int sum; //声明静态数据成员
};
int Myclass::Sum = 0;
Myclass::Myclass(int a , int b ,int c)
{
        this ->a = a;
        this ->b = b;
        this ->c = c;
        Sum + = a +b + c;   //非静态成员函数访问静态成员函数
}
void Myclass:GetSum(int a , int b ,int c)
{
        //cout<

你可能感兴趣的:(2018-01-23)