C++之关于static关键字的充电---补充(7)《Effective C++》
来源:互联网 发布:淘宝美德威萨克斯 编辑:程序博客网 时间:2024/05/22 02:05
终于有时间啦,可以将以前挖的坑填啦!
C++中的static与C语言有什么不同呢?我们指导C++语言添加了OOP思想,相对于C语言中的static有了新的引用场景,下面我们就来分析一下C++中C语言部分的static属性和C++ OOP部分的static属性!
C语言部分static:
1)static局部变量
static局部变量在函数中调用的时候会最终返回的最新的static成员值,这个特性我们姑且称之为“幻影”,看起来应该是以前的值,但是函数执行之后,static成员变量值总是会被更新为最新的值!
#include <iostream>#include <string>using namespace std;int& hel(int t){ static int i = t + 1; return i;}int main(){ int i = 10, j = 100; cout << hel(i) << " " << hel(j) << endl; if (hel(i) == hel(j)){ cout << "true" << endl; } else{ cout << "false" << endl; } return 0;}
运行结果为:
2)static全局变量
可以发现,当调用static全局变量的时候,会有相应的逻辑和存储,因此,不会出现像static局部变量那样总是返回当前值的行为!
#include <iostream>#include <string>using namespace std;static int i = 10;int hel(){ i++; return i;}int main(){ cout << i << endl; cout << hel() << endl; cout << hel() << endl; if (hel() == hel()){ cout << "true" << endl; } else{ cout << "false" << endl; } return 0;}
运行结果为:
3)static函数
static函数和static成员变量一样,具有两个属性:
- 不能被其他文件所引用;
- 其他文件中可以定义同名的函数;
test1.cpp
#include <iostream>using namespace std;static void hello(){ cout << "hello" << endl;}
test.cpp
#include <iostream>#include <string>using namespace std;extern void hello();int main(){ hello(); return 0;}
我们可以发现报错:
error LNK2019: 无法解析的外部符号 “void __cdecl hello(void)” (?hello@@YAXXZ),该符号在函数 _main 中被引用
如果我们改为如下代码呢?
test1.cpp
#include <iostream>using namespace std;static void hello(){ cout << "hello" << endl;}
test.cpp
#include <iostream>#include <string>using namespace std;extern void hello();(static/non-static) void hello(){ cout << "hahaha" << endl;}int main(){ hello(); return 0;}
运行结果为:
C++ OOP中的特性呢?
1)static成员变量
static成员变量属于整个类,值也有类在类外进行初始化设计;可以被static成员函数或者普通成员函数调用;
2)static成员函数
static成员函数只能对static成员变量进行修改,不能调用普通成员变量。
加油哈,各位小伙伴们,越过雷区,就是通天大道,敢越雷池半步一步才只是一个开端,不怕荆棘,勇于钻研,每一天都是一段最棒的旅程,加油啦!!!
- C++之关于static关键字的充电---补充(7)《Effective C++》
- C++中的virtual关键字---补充(1)《Effective C++》
- C语言之旅(7)关键字static的作用
- static关键字的作用(c&&c++)
- C语言之static关键字的使用
- 关于c++static关键字和extern关键字
- C语言关键字之static
- C/C++关键字之static
- C++之函数返回局部变量的初级探索---补充(3)《Effective C++》
- C++之返回值为reference引用的情况---补充(6)《Effective C++》
- C++之指针数组和数组指针的区别---补充(9)《Effective C++》
- C++之数组名和指针的区别---补充(10)《Effective C++》
- C++之创建自定义类型的数组---补充(17)《Effective C++》
- static关键字的用法(C++)
- static 关键字的用法(c语言)
- C语言的static关键字
- C语言的static关键字
- C#: static关键字的作用
- 【脚本语言系列】关于Python基础知识装饰器,你需要知道的事
- 血管疼#6
- 深入学习consul
- 【NIO总结】—NIO中的通道
- 保存bitmap 图片路径
- C++之关于static关键字的充电---补充(7)《Effective C++》
- 机器学习和数据挖掘(6):雷蒙保罗MAPA泛化理论
- 数学模型的适用范围
- A_S_M
- poj3281 Dining 题解
- 2017年7月22日20:45:16
- MapReduce编程基础(一)——基础知识
- 按图形输出
- 最大子矩阵(悬挂线)