#includeusing 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 seconds2 static 静态局部变量#includeusing 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 seconds3 简化观察#includeusing 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#includeusing 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关键字.



