我们学习C语言时会在变量的作用域中学到,一个变量可能是局部变量,也可能是全局变量,还有可能是静态变量,及寄存器变量。当然这么变量的不同全是因为变量存储位置不同,我们在学习C++第一章节时也提到C++语言在生成汇编时,C++编译器会按排不同的数据和代码在不同的存储区域。其中这里我们将要学习的静态成员和静态函数,它们都是存储在全局区或者叫静态区,是由不同的对象共同拥有一份拷贝。

【1】静态成员变量 ,类的成员变量存储在静态区,所有对象共享。定义格式:static 变量类型 变量名。初始化在外面。

#include <iostream.h>

class CStudent

{

public:

void get();

private:

static int count;

}

int CStdudent::count = 0; //初始化静态变量 使用时也可以直接 CStudent::count使用(当然这个要取决你的权限是public还private)

【2】静态成员函数 类成员函数,可以由类直接引用的。定义格式 staic 函数类型 函数名

#include <iostream.h>

class CStudent

{

public:

static void get(); //这里静态函数声明前要加static

private:

static int count;

}

void CStudent::get()  //这里静态函数前不需要加static.

{

++count;   //这里不能使用this 指针。并且因为这是静态函数,所以不能使用非静态成员变量。

}

void main()

{

CStudent stu;

CStudent::get(); //类可以直接使用静态函数

stu.get();

cout<&lt;CStudent::count&lt;&lt;endl;  //类可以直接使用静态成员变量。

cout&lt;&lt;stu.count&lt;&lt;endl;

}

下面是结合前面的友元函数与友元类的一个综合的例子:

#pragma once
#include&lt;iostream>

class CStudent
{
private:
    char m_name[20];
    int age;
   
public:
    CStudent(void);
    CStudent(char *name, int age);
    CStudent(const CStudent &student);
    void initialize(char *name,int age);
    void output();
    void add(int score);
    static void  sub(int score);
    ~CStudent(void);
    friend CStudent &input(CStudent &student,char *name,int age);
    friend class CTeacher;
    static int score;

};

#include "CStudent.h"
#include<string.h>

int CStudent::score = 0;
CStudent::CStudent(void)
{

}
CStudent::CStudent(char *name,int age)
{
    strcpy(this-&gt;m_name,name);
    this-&gt;age = age;
}

void CStudent::initialize(char *name,int age)
{
    strcpy(this-&gt;m_name,name);
    this-&gt;age = age;
}

CStudent::~CStudent(void)
{
}
void CStudent::output()
{
     std::cout<&lt;"name is "&lt;&lt;this->m_name<&lt;"   "&lt;&lt;this->age&lt;&lt;std::endl;
}

void CStudent::add(int score)
{
    CStudent::score+=score;
}

void CStudent::sub(int score)
{
    CStudent::score-=score;
   
}


class CTeacher
{
public:
    CStudent &visit(CStudent &student,char *name,int age);
};

CStudent& CTeacher::visit(CStudent &student,char *name,int age)
{
    strcpy(student.m_name,name);
    student.age = age;
    return student;
}

CStudent& input(CStudent &student,char *name,int age)
{
    strcpy(student.m_name,name);
    student.age = age;
    return student;
}


void main()
{
    CStudent stu("TOM",55);
    CStudent stu2;
    CTeacher teach1;
    input(stu,"JIM",66);
    stu.output();
    teach1.visit(stu,"AMMY",18);
    stu.output();
    stu.add(10);
    stu.add(15);
    std::cout&lt;&lt;"score "&lt;&lt;CStudent::score&lt;&lt;std::endl;
    CStudent::sub(10);
    std::cout&lt;&lt;"score "&lt;&lt;CStudent::score&lt;&lt;std::endl;
   
    system("pause");
}