zoukankan      html  css  js  c++  java
  • c++ 静态成员

    静态成员变量

    #include <iostream>
    using namespace std;
    #include <string>
    
    class Person
    {
    public:
    
        static int m_A;//静态成员变量
    
        //静态成员变量特点:
        //1 在编译阶段分配内存
        //2 类内声明,类外初始化
        //3 所有对象共享一份数据
    
    private:
        static int m_B;//静态成员变量也是有访问权限的
    };
    int Person::m_A = 10;
    int Person::m_B = 10;
    
    void test01() 
    {
        //静态成员变量两种访问方式
    
        //1、通过对象
        Person p1;
        p1.m_A = 100;
        cout << "p1.m_A = " << p1.m_A << endl;
    
        Person p2;
        p2.m_A = 200;
        cout << "p1.m_A = " << p1.m_A << endl;//共享同一份数据
        cout << "p2.m_A = " << p2.m_A << endl;
    
        //2、通过类名
        cout << "m_A = " << Person::m_A << endl;
    
        //cout << "m_B = " << Person::m_B << endl; //私有权限访问不到
    }
    
    
    int main()
    {
        
        test01();
    
        system("pause");
        return 0;
    
    }

    静态成员函数

    #include <iostream>
    using namespace std;
    #include <string>
    
    class Person
    {
    public:
    
        //静态成员函数特点:
        //1、程序共享一个函数
        //2、静态成员函数只能访问静态成员变量
    
        static void func()
        {
            cout << "func调用" << endl;
            m_A = 100;
            //m_B = 100;//错误,不可以访问非静态成员变量
        }
        static int m_A;//静态成员变量
        int m_B;
    
    private:
    
        //静态成员函数也是有访问权限的
        static void func2()
        {
            cout << "func调用" << endl;
        }
    };
    
    int Person::m_A = 10;
    
    void test01()
    {
        //静态成员变量两种访问方式
    
        //1、通过对象
        Person p1;
        p1.func();
    
        //2、通过类名
        Person::func();
    
    
        //Person::func2(); //私有权限访问不到
    }
    
    int main()
    {
        
        test01();
    
        system("pause");
        return 0;
    
    }
  • 相关阅读:
    logback-spring.xml配置文件详解
    SpringBoot-Controller接收参数的几种常用方式
    spring boot配置定时任务设置
    SpringCloud 配置文件 application.yml和 bootstrap.yml区别
    ajax/get请求
    ajax封装2
    ajax封装1
    楼层特效
    旋转动画
    联动动画
  • 原文地址:https://www.cnblogs.com/keepma/p/15555607.html
Copyright © 2011-2022 走看看