static修饰的成员称为静态成员,它分为两种静态数据成员和静态函数成员它们的书写方式分别为 static int a ;static void fun() ;
静态成员变量
static成员变量属于类,不属于某个具体的对象,即使创建多个对象也只能分配一个空间,
static成员变量必须在类的声明外部初始化
如
#include <iostream>
using namespace std ;
class Stu
{
public :
static int a ; //在类的外部声明
Stu()
{
a = 12 ;
}
};
int Stu::a = 0 ;
int main()
{
cout << Stu::a << endl ;
Stu s ;
cout << s.a << endl ;
return 0 ;
}
结果时
0
12 //因为在构造函数中重新对a进行了赋值
静态成员不能在类的内部进行初始化,当然如果你坚持要在类的内部进行初始化,有一部分是可以的
如静态常量整型数据成员就可以在类的内部进行初始化,如刚才的static int a ;如果直接对a进行赋值那么会提示错误,我们可以在int前面加const来对a进行赋值,形如static const int a = 12 ;这样就可以对a进行赋值了,当然只有整型可以,如:int char,
静态成员变量在初始化的时候不用在前面加static,但必须有数据类型
下面写个小程序对static进行理解
#include<iostream>
using namespace std;
class Student
{
private :
static int a ;
public:
Student ()
{
a++ ;
}
void show()
{
cout << "现在是:" << a << endl ;
}
};
int Student::a = 0 ;
int main ()
{
Student s[5] ;
for(int i = 0 ; i < 5 ; i++)
{
s[i].show();
}
return 0 ;
}
通过结果可以看出,每个结果都是5,其实static成员变量和普通的static成员变量一样,都在内存分区中的全局数据区分配内存,在程序结束时才释放,这意味着static成员变量不随对象的创建而分配内存,在对象销毁时释放内存,在提醒一下静态成员变量必须初始化,而且只能在类的外部进行初始化
静态成员函数
普通成员函数可以访问所有成员,而静态成员函数只能访问静态成员
用下面列子求学生人数和学生总分数
#include<iostream>
using namespace std;
class Student
{
private:
int m_id ;
int m_score ;
int m_count ;
public:
Student (int id,int score,int count) ;
void show() ;
public:
static int getcount() ; // 静态成员函数
static int getscore() ;
public:
static int gcount ; //静态成员变量 定义总人数
static int gscore ; //定义总分数
};
int Student::gcount = 0 ; //初始化总分数和总人数
int Student::gscore = 0 ;
Student::Student(int id,int score,int count) : m_id(id) , m_score(score) ,m_count(count)
{
gcount++ ; // 每次调用一次函数gcount+1
gscore += score ; // 每调用一次,相加
}
void Student::show()
{
cout << "id : " << m_id << " "
<< "count : " << m_count << " "
<< "score : " << m_count << " "
<< endl ;
}
int Student::getcount()
{
return gcount ;
}
int Student::getscore()
{
return gscore ;
}
int main()
{
Student s1(1,1,1) ;
s1.show() ;
Student s2(2,2,2) ;
s2.show() ;
Student s3(3,3,3) ;
s3.show() ;
Student s4(4,4,4) ;
s4.show() ;
int g1 = Student::getcount() ;
int g2 = Student::getscore();
cout << "总人数" << g1 << " "<< "总分数" << g2 << endl ;
return 0 ;
}
根据结果分析:总人数和总分数通过静态成员函数得到,