静态成员数据与函数


#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;
}

原文地址:https://www.cnblogs.com/w413133157/p/1654346.html