zoukankan      html  css  js  c++  java
  • 静态成员数据与函数


    #include "stdafx.h"
    #include <iostream.h>
    #include <string.h>

    //
    设计一个学生类,可以统计学生的总人数

    void GetName()
    {
        cout << "gobal fun" << endl;
    }

    class student
    {
    public:
        char m_szName[32];
    public:
        static int m_nStudentCount;  
        //
    静态的数据成员 
        //
    存在全部数据区,不在具体的对象中
        //
    和类型相关,和对象无关
    public
        student( const char* pstrName )
        {
            m_nStudentCount++;
            strcpy(m_szName,pstrName);  
        }
        ~student( )
        {
            if ( m_nStudentCount > 0 )
            {
                m_nStudentCount--;
            }
        }
        const char* GetName() const
        {
            //::GetName();       
            //m_szName[0] = 'A';
           
            cout << m_nStudentCount << endl;
           
            return m_szName; 
        }
       
        //
    静态成员函数中没有this指针
        static int GetStaictCount()
        {
            //cout << this->m_szName[0] << endl;
            return m_nStudentCount; 
        }
        static const char* GetStaictNameByObj( const student * pObj )
        {
            GetStaictCount();
           
            //
    如果在静态成员函数中要访问非静态函数,要传入对象地址
            pObj->GetName();
           
            return pObj->m_szName; 
        }
    };

    //
    静态数据成员的初始值,在类外定义
    int student::m_nStudentCount = 0;

    int main(int argc, char* argv[])
    {
        cout << student::GetStaictCount() << endl;
       
        student stu3("
    王五");
       
        student *pStu1 = new student("
    张三");
       
        student *pStu2 = new student("
    李四");
       
        cout << student::m_nStudentCount << endl;
       
        cout << &pStu1->m_nStudentCount  << endl;
        cout << &pStu2->m_nStudentCount << endl;
       
        cout << pStu1->GetName() << endl;
       
        cout << student::GetStaictCount() << endl;
       
        cout << student::GetStaictNameByObj( pStu1 ) << endl;
       
        if ( pStu1 )
        {
            delete pStu1;
            pStu1 = NULL;
        }
        if ( pStu2 )
        {
            delete pStu2;
            pStu2 = NULL;
        }
        return 0;
    }

  • 相关阅读:
    Go语言:如何解决读取不到相对路径配置文件问题
    Go组件学习:如何读取ini配置文件
    PMP学习笔记(一)
    SpringBoot安装与配置
    Homebrew中国镜像安装与配置
    Nginx日志常见时间变量解析
    openresty如何完美替换nginx
    Golang防止多个进程重复执行
    Windows 10 中CPU虚拟化已开启,但是docker无法运行
    彻底理解Python多线程中的setDaemon与join【配有GIF示意】
  • 原文地址:https://www.cnblogs.com/w413133157/p/1654346.html
Copyright © 2011-2022 走看看