前言
本文主要给大家介绍了关于c++中static修饰符的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。
下面一段是引用自effective c++ 中的一句话:
所谓的static对象,其寿命是从构造出来到程序结束为止(以下文章不再赘诉)。因此stack和heap-base对象都被排除。这种对象包括global对象,定义于namespace作用域内的对象,在classes内,在函数内,以及在file作用域内被声明为static的对象。
所以static在c++中可以存在在一下几种情况:
1.存在于全局作用域中的静态变量
//全局可访问,在内存中只有一份拷贝,可被很多函数修改。
#include <iostream>
static int i = 1; //作用域是整个file
void get(){
std::cout << "in func , the i is " << i << std::endl;
}
int main(){
std::cout << "the i is " << i << std::endl;
get();
return 0;
}
2.存在于函数当中的静态变量
// 只能在这个函数中才能被调用。
// 函数调用结束后,一般局部变量都被回收了,静态变量还存在
#include <iostream>
void get(){
static int i = 1;
std::cout << "the i is " << i << std::endl;
i++;
}
int main(){
get(); // i = 1
get(); // i = 2
std::cout << "the i is " << i << std::endl; // 这种是错误的
return 0;
}
3.存在于类的成员变量中的静态变量
//其实原理跟函数中的静态变量类似,类实例化出来的对象被销毁后,
// 但是类变量(静态成员变量)还是存在在内存中的
#include <iostream>
class Widget{
public:
Widget(int i){
a = i;
}
void get();
private:
static int a; // 声明静态变量
};
int Widget::a = 1; // 由于是类变量不是属于专属于一个对象的,被所有对象共享
// 所以需要在类外定义
void Widget::get(){
std::cout << "the a is " << a++ << std::endl;
}
int main(){
Widget w(1);
w.get(); // a = 1
w.get(); // a = 2
return 0;
}
4.存在于类中成员函数中的静态变量
#include <iostream>
class widget{
public:
widget(){}
void get();
};
void widget::get(){
static int i = 1;
//成员函数中的静态变量的作用域范围跟普通局部变量的作用域范围是一样的
std::cout << "in func, the i is " << i++ << std::endl;
}
int main(int argc, char const* argv[])
{
widget w1;
w1.get(); // in func, the i is 1
widget w2;
w2.get(); // in func, the i is 2
return 0;
}
5.存在于命令空间中的静态变量
#include <iostream>
namespace Widget {
static int i = 1; // 在该命名空间可用
void get(){
std::cout << "the i is " << i++ << std::endl;
}
} // namespace Widget
int main (){
using namespace Widget;
get(); //the i is 1
get(); // the i is 2
return 0;
}










