static&const
- 1、static关键字
-
- 面向过程
-
- 静态全局变量
- 静态局部变量
- 静态函数
- 面向对象
-
- 静态成员变量
- 静态成员函数
- 2、const关键字
1、static关键字
总结static的作用:
- 使得文件外部不能访问,文件外可以创建同名变量或者函数。
- 保留上一时刻的值,只能进行一次初始化操作。
面向过程
静态全局变量
在全局变量前加上
static
关键字,使得被修饰的变量不能被其他文件调用。例子:
//Example 2
//File1
#include <iostream.h>
void fn();
static int n; //定义静态全局变量
void main()
{
n=20;
cout<<n<<endl;
fn();
}
//File2
#include <iostream.h>
extern int n; //编译时报错;
void fn()
{
n++;
cout<<n<<endl;
}
编译时报错,体现作用1。
静态局部变量
在局部变量前加上
static
关键字,使得被修饰的变量不能被其他文件调用。例子:
#include <iostream>
using namespace std;
void fn();
void main()
{
fn();
fn();
fn();
system("pause");
}
void fn()
{
static int n = 10;
cout << n << endl;
n++;
}
输出结果:
10
11
12
体现作用2
静态函数
其他文件不能访问静函数,体现作用1。
面向对象
静态成员变量
与面向过程中的静态局部变量类似,例子:
// Myclass.h
#pragma once
class Myclass
{
int a, b, c;
static int sum;
public:
void GetSum();
Myclass(int a, int b, int c);
~Myclass();
};
// Myclass.cpp
#include "Myclass.h"
#include<iostream>
using namespace std;
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()
{
cout << "sum=" << sum << endl;
}
Myclass::~Myclass()
{
}
int main()
{
Myclass a(1, 2, 3);
a.GetSum();
Myclass b(4, 5, 6);
b.GetSum();
a.GetSum();
system("pause");
return 0;
}
静态成员函数
静态成员函数不含有this指针,只能访问静态成员变量和静态成员函数,不能访问非静态成员变量和非静态成员函数。其存在只是为了与静态成员变量相对应。
2、const关键字
作用:
将变量设置为只读。
例如:
const int a = 1;
a = 2; //编译错误
特殊情况,修饰指针时:
const * int pa = &a; //指向的对象只读
int * const pa = &a; //指针本身只读
const * const int pa = &a; //指针指向的对象和本身都只读
记忆方法,
const右边是谁则修饰谁。如:
const *
修饰指针指向的对象;
const pa
修饰指针本身。
参考:https://www.cnblogs.com/BeyondAnyTime/archive/2012/06/08/2542315.html