C++学习--static

1、静态的全局变量:改变量只能在本文件使用,其他文件无法使用
2、静态的局部变量:延长变量生命周期,函数运行结束后变量不释放,到程序结束后才释放
3、静态的函数:该函数只能在本文件使用

静态成员函数 -----> 只能使用静态的成员变量 

静态的成员变量
    1、不是对象的属性,可以理解为 类的属性
    2、所有对象共享该变量
    3、必须在类的外部进行初始化


静态成员使用(函数和变量):
1、和普通变量 通过对象调用:对象.属性
2、通过类名调用:类名::属性

#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;

// 1、静态的全局变量:改变量只能在本文件使用,其他文件无法使用
// 2、静态的局部变量:延长变量生命周期,函数运行结束后变量不释放,到程序结束后才释放
// 3、静态的函数:该函数只能在本文件使用

class Test
{
public:
	// 静态成员函数 -----> 只能使用静态的成员变量  
	static void print()
	{
		// cout << "a = " << a << endl;
		cout << "b = " << b << endl;
	}
	
public:
	int a;
	
	// 静态的成员变量
	// 1、不是对象的属性,可以理解为 类的属性
	// 2、所有对象共享该变量
	// 3、必须在类的外部进行初始化
	static int b;    
};
int Test::b = 10;  // 在类的外部进行初始化   

// 静态成员使用:
// 1、和普通变量 通过对象调用:对象.属性
// 2、通过类名调用:类名::属性
int main1()
{
	Test t1;
	cout << t1.b << endl;
	
	t1.b = 123;
	Test t3;
	cout << t3.b << endl;
	
	Test::b = 567;  // 通过类名使用静态成员
	cout << t1.b << endl;
	
	return 0;
}

int main()
{
	Test t1;
	Test::b = 20;
	Test::print();
	t1.print();//两种调用方式
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/ls_dashang/article/details/82975716