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

来源:互联网 发布:淘宝美德威萨克斯 编辑:程序博客网 时间:2024/05/22 02:05

终于有时间啦,可以将以前挖的坑填啦!
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成员变量进行修改,不能调用普通成员变量。

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

原创粉丝点击