面试官:聊聊 C++ static 和 const

static 关键字
  1. 将具有 外部链接 属性的变量/函数转换为 内部链接

    全局变量和函数的链接属性默认为外部链接(对其他文件可见)

    我们在 test.cpp 文件中定义全局变量global,并申明函数 func()

    test.cpp

    #include<iostream>
    
    using namespace std;
    
    void func();
    
    int global = 0;
    
    
    int main()
    {
         
    	func(); // 调用 test2.cpp 中定义的 func 函数
    }
    

    test2.cpp文件中定义函数func()并声明变量global

    test2.cpp

    #include<iostream>
    
    extern int global;
    
    void func()
    {
         
        // 使用 test.cpp 中定义的 global 变量
    	std::cout << "global int test2.cpp: " << global << std::endl; 
    }
    

    编译两个文件并运行,得到输出:

    global int test2.cpp: 0
    

    现在我们使用 static 声明函数和变量:

    static int global = 0;
    
    static void func()
    {
         
    std::cout << "global int test2.cpp: " << global << std::endl;
    }
    

    编译发现报错:

    错误	LNK2019	无法解析的外部符号 "void __cdecl func(void)" (?func@@YAXXZ),函数 _main 中引用了该符号	
    
    错误	LNK2001	无法解析的外部符号 "int global" (?global@@3HA)	
    

    此时 globaltest2.cpp 是不可见的;func() 函数对 test.cpp 是不可见的

  2. 将具有 自动存储期限 的变量转换为 静态存储期限

    auto变量(函数局部变量)都是在栈内存区存放,函数结束后就自动释放。但是全局的和函数内定义的static变量都是存放在数据区的,且只存一份,只在整个程序结束后才自动释放。

    void func()
    {
         
        // static 类型变量只在程序第一次执行到定义时初始化
    	static int i = 0; 
    	int j = 0;
    	cout << "i = "<< i++ << " j = " << j++ << endl;
    }
    int main()
    {
         
    	func();
    	func();
    	func();
    }
    

    输出:

    i = 0 j = 0
    i = 1 j = 0
    i = 2 j = 0
    
  3. C++ 中 静态成员变量 :整个类共享。必须在类外定义

    class A
    {
         
    private:
    	int _i;
    	static int _si;
    
    public:
    	static int _hi;
    	static void print();
    	void show();
    };
    
    // 只有定义时可以使用 类名:: 访问到,其他时候不可以
    int A::_si = 10;
    int A::_hi = 20;
    
    int main()
    {
         
    	A a;
    
    	// 不在类外定义,会报连接错误
    	cout << A::_hi 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值