C++之关于static关键字的充电---补充(7)《Effective C++》

1 篇文章 0 订阅

终于有时间啦,可以将以前挖的坑填啦!
C++中的static与C语言有什么不同呢?我们指导C++语言添加了OOP思想,相对于C语言中的static有了新的引用场景,下面我们就来分析一下C++中C语言部分的static属性和C++ OOP部分的static属性!

C语言部分static:

1)static局部变量
static局部变量在函数中调用的时候会最终返回的最新的static成员值,这个特性我们姑且称之为“幻影”,看起来应该是以前的值,但是函数执行之后,static成员变量值总是会被更新为最新的值!

#include <iostream>
#include <string>
using namespace std;
int& hel(int t){
    static int i = t + 1;
    return i;
}

int main(){
    int i = 10, j = 100;
    cout << hel(i) << " " << hel(j) << endl;
    if (hel(i) == hel(j)){
        cout << "true" << endl;
    }
    else{
        cout << "false" << endl;
    }
    return 0;
}

运行结果为:
这里写图片描述
2)static全局变量

可以发现,当调用static全局变量的时候,会有相应的逻辑和存储,因此,不会出现像static局部变量那样总是返回当前值的行为!

#include <iostream>
#include <string>
using namespace std;
static int i = 10;
int hel(){
    i++;
    return i;
}

int main(){
    cout << i << endl;
    cout << hel() << endl; 
    cout << hel() << endl;
    if (hel() == hel()){
        cout << "true" << endl;
    }
    else{
        cout << "false" << endl;
    }
    return 0;
}

运行结果为:
这里写图片描述

3)static函数
static函数和static成员变量一样,具有两个属性:

  • 不能被其他文件所引用;
  • 其他文件中可以定义同名的函数;

test1.cpp

#include <iostream>
using namespace std;
static void hello(){
    cout << "hello" << endl;
}

test.cpp

#include <iostream>
#include <string>
using namespace std;
extern void  hello();
int main(){
    hello();
    return 0;
}

我们可以发现报错:
error LNK2019: 无法解析的外部符号 “void __cdecl hello(void)” (?hello@@YAXXZ),该符号在函数 _main 中被引用
如果我们改为如下代码呢?

test1.cpp

#include <iostream>
using namespace std;
static void hello(){
    cout << "hello" << endl;
}

test.cpp

#include <iostream>
#include <string>
using namespace std;
extern void  hello();
(static/non-static) void hello(){
    cout << "hahaha" << endl;
}
int main(){
    hello();
    return 0;
}

运行结果为:
这里写图片描述

C++ OOP中的特性呢?

1)static成员变量
static成员变量属于整个类,值也有类在类外进行初始化设计;可以被static成员函数或者普通成员函数调用;
2)static成员函数
static成员函数只能对static成员变量进行修改,不能调用普通成员变量。

加油哈,各位小伙伴们,越过雷区,就是通天大道,敢越雷池半步一步才只是一个开端,不怕荆棘,勇于钻研,每一天都是一段最棒的旅程,加油啦!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值