静态成员:由关键字static修饰说明的类成员,称为静态成员。
虽然使用static修饰说明,但与函数中的静态变量有明显差异。
类的静态数据成员为其所有对象共享,不管有多少对象,静态数据成员只有一份存于共有内存中。
静态数据成员由于其共享性,所以在类外部(友元)访问时使用如下格式:类名::静态数据成员名
静态数据成员在类外初始化。
普通方法可以访问静态和普通变量,静态方法仅可以访问静态变量(原因是静态方法不含有this指针)
//Test.h
#include<iostream>
using namespace std;
class ST
{
private:
int a;
static double count_b;
public:
ST(int _a=0):a(_a)
{
this->a = _a;
}
friend void Show();
static void Add_count();
void Add(); //普通方法可以访问静态和普通变量,静态方法仅可以访问静态变量(原因是静态方法不含有this指针)
void print()const; //const保证this指向的数据不被修改,因为其等价于 void print(const ST *const this),
ST(ST &t); //也因此,常函数内部不允许调用普通函数
~ST(){}
};
void Show()
{
cout<<"count_b = "<<ST::count_b<<endl;
}
void ST::print()const
{
cout<<this->a<<" ,"<<count_b<<endl;
}
void ST::Add_count()//在类外部实现时不需要在加上static
{
++count_b;
}
void ST::Add()
{
++this->a;
++count_b;
}
ST::ST(ST& t)
{
this->a = t.a;
}
double ST::count_b = 0;
常方法认为其隐含this指针所指向的数据常量
例如void print()const 等价于void print(const Test *const this)
常方法不允许调用普通方法,因为其this参数和普通方法不同
//Test.cpp
#include<iostream>
#include"Test1.h"
using namespace std;
void main()
{
ST st(11),st1(12);
st.Add_count();
st.Add();
Show();//访问静态数据成员count_b,所以并不需要某个对象的调用,体现出静态数据成员的共享性和其独立性(并不和对象依存)
}
运行结果