美文网首页
C/C++第九课~static、extern 关键字和位运算符、

C/C++第九课~static、extern 关键字和位运算符、

作者: XX杰 | 来源:发表于2022-11-06 16:39 被阅读0次

    1、static 修饰局部变量可以在函数调用之间保持局部变量的值。不知道如何操作
    2、static 修饰符也可以应用于全局变量。当 static 修饰全局变量时,会使变量的作用域限制在声明它的文件内。
    3、在 C++ 中,当 static 用在类数据成员上时,会导致仅有一个该成员的副本被类的所有对象共享。

    1、extern 存储类 用于提供一个全局变量的引用,全局变量对所有的程序文件都是可见的。

    #include <iostream>
    using namespace std;
    // 全局变量
    static int b = 12324;
    void func() {
        b--;
        cout<<b<<endl;
    }
    // extern 声明一个函数,在下面进行了实现
    extern void func2(int a);
    int main()
    {
        func();
        func2(12);
        return 0;
    }
    
    void func2(int a){
        a++;
        cout<<a<<endl;
    }
    

    2、运算符

    这里就不介绍 常用的运算符了。在java中经常使用。这里仅仅介绍一下位运算符

    假设变量 A 的值为 60,变量 B 的值为 13
    A = 0011 1100
    B = 0000 1101

    image.png
    image.png

    左移相当于 *2 右移 相当于 /2 取整

    3、函数返回数组

    数组中Why,需要使用 static 来返回

    #include <iostream>
    using namespace std;
    
    int * getArray(){
          //  不知道 Why,必须要用 static 来修饰
        static int a[5]={1,22,3,4,5};
        return a;
    }
    
    int main()
    {
        int *b=getArray();
        cout<<*(b+1)<<endl;
        return 0;
    }
    

    4、指针指向C++的类

    #include <iostream>
    using namespace std;
    
    class majie {
    public:
        int a=34567;
        int b=67;
    private:
        int c;
        int d=23;
    public:
    //  构造方法
        majie() {
    cout<<"majie"<<endl;
        }
    // 析构方法
        ~majie() {
    cout<<"~majie"<<endl;
        }
    };
    void func() {
        majie m = majie();
        majie *mj = &m;
    // 可以访问 public 不可以访问 private 中的成员
        cout<<mj->b<<endl;
    }
    int main()
    {
        func();
        cout<<"system exit"<<endl;
        return 0;
    }
    

    结果:

    majie
    67
    ~majie
    system exit

    由此可见,当在方法中的类 majie 结束使用的时候,自动调用其析构函数

    相关文章

      网友评论

          本文标题:C/C++第九课~static、extern 关键字和位运算符、

          本文链接:https://www.haomeiwen.com/subject/qpgbtdtx.html