C++ Primer Plus学习:第九章 内存模型和名称空间(1)

本文深入解析了C++中头文件、存储持续性、静态存储、动态存储及作用域的概念,通过实例展示了如何在代码中应用这些原理。
头文件
  同一个文件中,只能将头文件包含一次
  头文件
    如果文件名包含尖括号中,则C++编译器将在存储标准头文件的主机系统的头文件系统中查找
    如果文件名包含在双引号中,则编译器首先查找当前的工作目录或者源代码目录
存储数据
  自动存储持续性
    在函数定义中声明的变量(包括函数参数)的存储持续性是自动的
    在程序开始执行其所属的函数或者代码块时被创建,在执行完函数或者代码块时,它们使用的内存被释放
  静态存储持续性
    static关键字
    程序整个运行过程中都存在
    特征
      未被初始化的静态变量的所有位置都被设置为0
      只能使用常量表达式来初始化静态变量
  动态存储持续性
    new操作符分配的内存将一直存在,直到使用delete操作符将其释放或者程序结束为止
    另称:自由存储
作用域

  eg

#include <iostream>
using namespace std;

void oil(int x);

int main()
{
    int texas = 31;
    int year = 1999;
    
    cout<<"In main(),texas = "<<texas<<",&texas = "<<&texas<<endl;
    cout<<"In main(),year = "<<year<<", &year = "<<&year<<endl;
    
    oil(texas);
    cout<<"In main(),texas = "<<texas<<",&texas = "<<&texas<<endl;
    cout<<"In main(),year = "<<year<<", &year = "<<&year<<endl;
    
    system("pause");
    return 0;
    
    }

void oil(int x)
{
     int texas = 5;
     
     cout<<"In oil(),texas = "<<texas<<",&texas = "<<&texas<<endl;
     cout<<"In oil(),x = "<<x<<",&x = "<<&x<<endl;
     
     {
               int texas = 113;
               cout<<"In block(),texas = "<<texas<<",&texas = "<<&texas<<endl;
               cout<<"In block(),x = "<<x<<",&x = "<<&x<<endl;
               }
     cout<<"Post-block texas = "<<texas;
     cout<<",&texas = "<<&texas<<endl;
     
     }


  extern

#include <iostream>
using namespace std;
int tom = 3;
int dick = 30;
static int harry = 300;

void remote_access();

int main()
{
    cout<<"main() reports the following address:\n";
    cout<<&tom<<" = &tom,"<<&dick<<" = &dick.";
    cout<<&harry<<" = &harry\n";
    remote_access();
    
    system("pause");
    return 0;
    }

#include <iostream>
using namespace std;

extern int tom;
static int dick = 10;
int harry = 200;

void remote_access()
{
     cout<<"remote_access() reports the following address:\n";
     cout<<&tom<<" = &tom."<<&dick<<" = &dick.";
     cout<<&harry<<" = &harry";
     }


存储说明符
  auo
    自动变量
  register
    指示寄存器存储类型
  static
    作用域为整个文件,表示内部链接
    被用于局部声明中,表示局部变量的存储持续性
  extern
    声明引用在其他地方定义的变量
  mutable
    const
      内存被初始化后,程序便不能再修改
    volatile
      程序没有对内存单元进行修改,其值也可能发生变化
Note
  在多文件程序中,可以在一个文件(且只能在一个文件)中定义一个外部变量,使用该变量的其它文件必须使用关键字extern声明它
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值