zoukankan      html  css  js  c++  java
  • 全局变量和全局静态变量

    作用域:
    全局变量整个程序空间,全局静态变量只在包含它的cpp中使用,下面举个栗子

    global.h
    #ifndef GLOBAL_H
    #define GLOBAL_H
    
    static int gs_a;
    extern int g_b; //multiple definition,注意extern
    
    #endif // GLOBAL_H
    

    testa.h

    #ifndef TESTA_H
    #define TESTA_H
    
    class TestA
    {
    public:
        TestA();
    };
    
    #endif // TESTA_H
    

    testa.cpp

    #include "testa.h"
    #include "global.h"
    #include <iostream>
    
    TestA::TestA()
    {
        gs_a = 1;
        g_b = 1;
        std::cout << "TestA gs_a : " << gs_a << " g_b : " << g_b << std::endl;
    }
    

    testb.h

    #ifndef TESTB_H
    #define TESTB_H
    
    class TestB
    {
    public:
        TestB();
    };
    
    #endif // TESTB_H
    

    testb.cpp

    #include "testb.h"
    #include "global.h"
    #include <iostream>
    
    TestB::TestB()
    {
        gs_a = 2;
        g_b = 2;
        std::cout << "TestB gs_a : " << gs_a << " g_b : " << g_b << std::endl;
    }
    

    main.cpp

    #include <iostream>
    #include "global.h"
    #include "testa.h"
    #include "testb.h"
    
    int g_b = 0; //undefined reference to g_b,注意初始化
    int main(int argc, char *argv[])
    {
        gs_a = 3;
        g_b = 3;
        std::cout << "Main gs_a : " << gs_a << " g_b : " << g_b << std::endl;
        TestA ta;
        std::cout << "Main::TestA gs_a : " << gs_a << " g_b : " << g_b << std::endl;
        TestB tb;
        std::cout << "Main::TestB gs_a : " << gs_a << " g_b : " << g_b << std::endl;
        return 0;
    }

    输出:

    Main gs_a : 3 g_b : 3
    TestA gs_a : 1 g_b : 1
    Main::TestA gs_a : 3 g_b : 1
    TestB gs_a : 2 g_b : 2
    Main::TestB gs_a : 3 g_b : 2
    
  • 相关阅读:
    JavaScript常用设计模式
    js 判断l对象类型
    JavaScript编程(终极篇)
    微信小程序开发-滑动操作
    解决Jquery向页面append新元素之后事件的绑定问题
    C# list与数组互相转换
    C# “贝格尔”编排法
    C#数字格式化
    SQL从一个表查询数据插入/更新到另一个表
    全局唯一标识符 (GUID)
  • 原文地址:https://www.cnblogs.com/nuoforever/p/15103360.html
Copyright © 2011-2022 走看看