C++中参数的持续性,作用域和连接性。 稍稍看了会C++ Primer,然后把书中讲这部分的内容精简下。先给大家说下自动变量,这个是在函数中用的,我个人认为是比较多的一中变量。自动变量的修饰符是(auto),但一般情况下我们忽略它,它是在代码块中被创建,当代码块结束就消失的一种变量。它是存放在堆栈中,所以可想而知,当堆栈结束后,变量也不在了。接下来讲下自动变量中的寄存器变量,上面说了,变量放在堆栈中,所以会消耗内存,而寄存器变量则解决了这个问题,它需要在自动变量声明前加上一个“register”,这样编辑器就会去使用寄存器来处理变量。但记住一点,由于寄存器上没有地址,所以,对寄存器变量不能使用取地址符号。接下来说一下静态变量。这个是我个人感觉很头疼的一种变量。首先,静态存储持续性有三种链接性,1.外部链接性,2.内部链接性,3.无连接性。下面上一张表格,里面介绍了五种存储方式。
5种变量储存方式| 存储描述 | 持续性 | 作用域 | 链接性 | 如何声明 |
| 自动 | 自动 | 代码块 | 无 | 在代码块中,(auto) |
| 寄存器 | 自动 | 代码块 | 无 | 在代码块中,用register |
| 静态,无连接性 | 静态 | 代码块 | 无 | 在代码块中,用static |
| 静态,外部链接性 | 静态 | 文件 | 外部 | 在函数外面 |
| 静态,内部链接性 | 静态 | 文件 | 内部 | 在函数外面,使用关键字static |
我先贴这些上来,相信大家也都能看懂些,时间不早了,先睡觉去,明天晚上下班后,接着补充,到时候给大家上几段代码,然后介绍下命名空间,其实也是一种作用域。嘿嘿,先挖个坑在这,明天来填坑,啊不对。。12点了,是今天晚上。。。继续更新,接下来贴一段静态修饰的,外部链接性的例子
- #include <iostream>
-
- using namespace std;
- //注意warming变量
- double warming = 0.3; //全局变量 称为定义,给变量分配存储空间
-
- void update(double dt);
- void local();
-
- int main(){
- cout << "Global warming is " << warming << " degrees.
";
- update(0.1);
- cout << "Global warming is " << warming << " degrees.
";
- local();
- cout << "Global warming is " << warming << " degrees.
";
- return 0;
- }
-
- void update(double dt)
- {
- extern double warming; //引用外部变量 为0.3<SPAN> </SPAN>称为声明,不给变量分配存储空间
- warming += dt;
- cout << "UPdating gloabal warming to " << warming;
- cout << " degrees.
";
- }
-
- void local()
- {
- double warming = 0.8; //隐藏了外部变量 为0.8
- cout << "Local warming = " << warming << " degrees.
";
- cout << "the global waming is " << ::warming;
- }
这个注释蛮清楚了,最好运行下自己看看。 下面两段代码是静态修饰,内部链接性的例子file1.cpp
- #include <iostream>
-
- int tom = 3; //
- int dick = 30; //
- static int harry = 300; //内部链接性,只在该函数内部可用。
-
- void remote_access();
-
- int main()
- {
- using namespace std;
- cout << "main()reports the following addresses:
";
- cout << &tom << " = &tom, " << &dick << " = &dick, ";
- cout << &harry << " = &harry
";
- cout << tom << " " << dick << " " << harry << " " << endl; // 3 30 300
- remote_access();
- return 0;
- }
file2.cpp
- #include <iostream>
-
- extern int tom;
- static int dick = 10; //内部链接性
- int harry = 200;
-
- void remote_access()
- {
- using namespace std;
- cout << "remote_access() reports the following address:
";
- cout << &tom << " = &tom, " << &dick << " = &dick, ";
- cout << &harry << " = &harry
";
- cout << tom << " " << dick << " " << harry << " " << endl; // 3 10 200
- }