zoukankan      html  css  js  c++  java
  • 变量作用域

    1)全局变量

    2)文件级变量。

    3)函数级static变量。

    4)函数内auto变量。

    5) 类内statci变量。

    #include <stdio.h>
    #include <iostream>
    #include <sstream>
    #include "myclass.h"
    
    using namespace std;
    
    int g_int=4;//1)    heap中,所有文件都可以用.只要在所用的文件写上 extern int g_int;
    static int s_int=5;//2)   heap中,但只有本文件才可以使用.
    
    int* testLS_int();
    int main()
    {
        int int_l=4;//4)函数内部使用
        cout<< *testLS_int()<<endl;
        cout<< *testLS_int()<<endl;
        cout<< *testLS_int()<<endl;
        cout<< *testLS_int()<<endl;
        cout<< *testLS_int()<<endl;
    
        return 0;
    }
    
    int* testLS_int()
    {
        //3)函数类,静态变量.应该是编译时,已经放入数据区.程序加载时,放入heap中.
        //所以并不会如其他局部变量一样,每次到函数体,会在函数内(stack)加载一次.
        //所以作用很巧妙.local_static_int完全可以是一个类对象.返回地址变量也就是指针.而不会出错.
        static int local_static_int =0;
        ++local_static_int;
        return &local_static_int;
    }

    5) 类内statci变量。

    #include <stdio.h>
    #include <iostream>//cin,cout
    #include <sstream>//ss transfer.
    #include <fstream>//file
    #include "myclass.h"
    #include <list>
    #include <map>
    #include <vector>
    #include <algorithm>
    #include <memory>
    
    using namespace std;
    
    class book
    {
    public:
        int id;
        string name;
        static int pid;//这里不能赋值.除非是const类型.为什么编译器不让赋值呢?硬要加上这个语法的话,也不是不可以吧.可能是逻辑考虑吧.
        ~book()
        {
            cout<<"del"<<endl;
        }
    private:
    
    };
    
    
    void point(const book& myb)
    {
        book csharp=myb;
    }
    
    int book::pid=6;//类的static是存放于堆.必须在全局定义,编译器会放入堆中.
    int main()
    {
        book cadd;
        cadd.id=1;
        cadd.name="c++";
    
        book csharp=cadd;
    
        book::pid=8;
    
        cout<<csharp.pid<<endl;
    
       return 0;
    }
  • 相关阅读:
    序列终结者
    CF696C PLEASE
    [清华集训]Rmq Problem / mex
    CF786B Legacy
    链表结构详解
    synchronized同步方法和同步代码块的区别
    关于守护线程定义
    线程的优先级
    mysql查询当天的数据
    java以正确的方式停止线程
  • 原文地址:https://www.cnblogs.com/lsfv/p/6008328.html
Copyright © 2011-2022 走看看