1 局部变量
#include<iostream> 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="<<Sum<<std::endl; } int main() { Myclass M(1,2,3); M.GetSum(); Myclass N(4,5,6); N.GetSum(); M.GetSum(); return 0; }
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<iostream> 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="<<Sum<<std::endl; } int main() { Myclass M(1,2,3); M.GetSum(); Myclass N(4,5,6); N.GetSum(); M.GetSum(); return 0; }
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
留意
1.增加static后,这里Sum运行后没有初始化,对所有对象共享.
2.原文介绍
- 静态全局变量不能被其它文件所用;
- 其它文件中可以定义相同名字的变量,不会发生冲突;
3.原文:Arkin:C/C++ 中的static关键字.