栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++ Static使用

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++ Static使用

1 局部变量
#include
using namespace std;
class Myclass
{
public:
	Myclass(int a,int b,int c);
	void GetSum();
private:
	int a,b,c;
	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()
{
	std::cout<<"Sum="< 

VS code运行结果:

[Running] cd "/home/SoftApp/VScode/CPP_Study/" && g++ main.cpp -o main && "/home/SoftApp/VScode/CPP_Study/"main
Sum=6
Sum=15
Sum=6

[Done] exited with code=0 in 0.272 seconds
2 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;
}
int Myclass::Sum = 0;
void Myclass::GetSum()
{
	std::cout<<"Sum="< 

VS Code运行结果:

[Running] cd "/home/SoftApp/VScode/CPP_Study/" && g++ main.cpp -o main && "/home/SoftApp/VScode/CPP_Study/"main
Sum=6
Sum=21
Sum=21

[Done] exited with code=0 in 0.316 seconds
3 简化观察
#include
using namespace std;

void fn(){ 
	static int n=-1;
	n++; 
	cout< 
[Running] cd "/home/SoftApp/VScode/CPP_Study/" && g++ main.cpp -o main && "/home/SoftApp/VScode/CPP_Study/"main
0
1
2

[Done] exited with code=0 in 0.258 seconds
#include
using namespace std;

void fn(){ 
	int n=-1;
	n++; 
	cout< 
[Running] cd "/home/SoftApp/VScode/CPP_Study/" && g++ main.cpp -o main && "/home/SoftApp/VScode/CPP_Study/"main
0
0
0

[Done] exited with code=0 in 0.247 seconds
留意

1).增加static后,这里Sum运行后没有初始化,对所有对象共享.
2).原文介绍
- 静态全局变量不能被其它文件所用;
- 其它文件中可以定义相同名字的变量,不会发生冲突;
3).原文:Arkin:C/C++ 中的static关键字.

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/312345.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号