C++中参数的持续性,作用域和连接性


C++中参数的持续性,作用域和连接性。

稍稍看了会C++ Primer,然后把书中讲这部分的内容精简下。

先给大家说下自动变量,这个是在函数中用的,我个人认为是比较多的一中变量。自动变量的修饰符是(auto),但一般情况下我们忽略它,它是在代码块中被创建,当代码块结束就消失的一种变量。它是存放在堆栈中,所以可想而知,当堆栈结束后,变量也不在了。

接下来讲下自动变量中的寄存器变量,上面说了,变量放在堆栈中,所以会消耗内存,而寄存器变量则解决了这个问题,它需要在自动变量声明前加上一个“register”,这样编辑器就会去使用寄存器来处理变量。但记住一点,由于寄存器上没有地址,所以,对寄存器变量不能使用取地址符号。

接下来说一下静态变量。这个是我个人感觉很头疼的一种变量。

首先,静态存储持续性有三种链接性,1.外部链接性,2.内部链接性,3.无连接性。

下面上一张表格,里面介绍了五种存储方式。

5种变量储存方式
存储描述 持续性 作用域 链接性 如何声明
自动 自动 代码块 在代码块中,(auto)
寄存器 自动 代码块 在代码块中,用register
静态,无连接性 静态 代码块 在代码块中,用static
静态,外部链接性 静态 文件 外部 在函数外面
静态,内部链接性 静态 文件 内部 在函数外面,使用关键字static

我先贴这些上来,相信大家也都能看懂些,时间不早了,先睡觉去,明天晚上下班后,接着补充,到时候给大家上几段代码,然后介绍下命名空间,其实也是一种作用域。嘿嘿,先挖个坑在这,明天来填坑,啊不对。。12点了,是今天晚上。。。

继续更新,接下来贴一段静态修饰的,外部链接性的例子

  1. #include <iostream>   
  2.   
  3. using namespace std;  
  4. //注意warming变量   
  5. double warming = 0.3;               //全局变量 称为定义,给变量分配存储空间   
  6.   
  7. void update(double dt);  
  8. void local();  
  9.   
  10. int main(){  
  11.     cout << "Global warming is " << warming << " degrees.\n";  
  12.     update(0.1);  
  13.     cout << "Global warming is " << warming << " degrees.\n";  
  14.     local();  
  15.     cout << "Global warming is " << warming << " degrees.\n";  
  16.     return 0;  
  17. }  
  18.   
  19. void update(double dt)  
  20. {  
  21.     extern double warming;          //引用外部变量  为0.3<SPAN>    </SPAN>称为声明,不给变量分配存储空间   
  22.     warming += dt;  
  23.     cout << "UPdating gloabal warming to " << warming;  
  24.     cout << " degrees.\n";  
  25. }  
  26.   
  27. void local()  
  28. {  
  29.     double warming = 0.8;           //隐藏了外部变量 为0.8   
  30.     cout << "Local warming = " << warming << " degrees.\n";  
  31.     cout << "the global waming is " << ::warming;   
  32. }  
这个注释蛮清楚了,最好运行下自己看看。

下面两段代码是静态修饰,内部链接性的例子

file1.cpp

  1. #include <iostream>   
  2.   
  3. int tom = 3;                //   
  4. int dick = 30;              //   
  5. static int harry = 300;     //内部链接性,只在该函数内部可用。   
  6.   
  7. void remote_access();  
  8.   
  9. int main()  
  10. {  
  11.     using namespace std;  
  12.     cout << "main()reports the following addresses: \n";  
  13.     cout << &tom << " = &tom, " << &dick << " = &dick, ";  
  14.     cout << &harry << " = &harry\n";  
  15.     cout << tom << ' ' << dick << ' ' << harry << ' ' << endl;        // 3 30 300   
  16.     remote_access();  
  17.     return 0;  
  18. }  
file2.cpp
  1. #include <iostream>   
  2.   
  3. extern int tom;  
  4. static int dick = 10;           //内部链接性   
  5. int harry = 200;  
  6.   
  7. void remote_access()  
  8. {  
  9.     using namespace std;  
  10.     cout << "remote_access() reports the following address: \n";  
  11.     cout << &tom << " = &tom, " << &dick << " = &dick, ";  
  12.     cout << &harry << " = &harry\n";  
  13.     cout << tom << ' ' << dick << ' ' << harry << ' ' << endl;        // 3 10 200   
  14. }  
  • 1
  • 2
  • 下一页

相关内容