C++学习笔记——static&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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值