//全局可访问,在内存中只有一份拷贝,可被很多函数修改。
#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;
}
// 只能在这个函数中才能被调用。
// 函数调用结束后,一般局部变量都被回收了,静态变量还存在
#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;
}
//其实原理跟函数中的静态变量类似,类实例化出来的对象被销毁后,
// 但是类变量(静态成员变量)还是存在在内存中的
#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;
}
#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;
}
#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;
}
// 其实跟一般的函数差不多,
// 但是它将该函数的链接属性限制为内链接,
//只能在本编译单元中使用(也就是本文件),
//不能被extern等在外部文件中引用
static void get(){
std::cout << "this is staic global func" << std::endl;
}
int main(){
get();
get();
return 0;
}
#include <iostream>
class Widget{
public:
Widget(int i){
a = i;
}
static void get(); // 声明静态函数
private:
static int a;
int b;
};
int Widget::a = 1;
void Widget::get(){
std::cout << b << std::endl; //这是错误的,因为静态函数和静态变量直接能够
// Widget::get()调用,不需要实例化,所以不能
// 调用只能实例化才能初始化的成员变量。
std::cout << a << std::endl; //ok
}
int main(){
Widget w(1);
w.get();
return 0;
}
#include <iostream>
class Widget{
public:
Widget(int i){
b = i;
}
void set() const;
private:
static int a;
int b;
};
int Widget::a = 1;
void Widget::set() const{
a++; //这是对的,因为是静态成员变量是类变量
b++; //错误的,普通成员变量是不能被常函数改变的。
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有