一.类的静态成员函数
如果类中需要统计多少个对象存在,C++有了类的静态成员变量和静态成员函数。
* 静态成员属于整个类所有,不需要依赖任何对象
* 可以通过类名直接访问public静态成员
* 可以通过对象名访问public静态成员
* 静态成员函数可以直接访问静态成员变量
* 可以通过类名直接访问public静态成员
* 可以通过对象名访问public静态成员
* 静态成员函数可以直接访问静态成员变量
静态成员变量的定义:
static 关键字修饰
静态成员变量不依赖任何对象,需要在类外单独分配空间。
Type ClassNmae::VarName;
#include <stdio.h>
class Test
{
private:
static int i;
public:
static int getValue()
{
return i;
}
static void setValue(int v)
{
i = v;
}
void print()
{
printf("%d\n",i);
}
};
int Test::i;
int main()
{
/*
没有声明对象,直接通过类调用成员函数。
*/
Test::setValue(10);
printf("%d\n",Test::getValue());
Test t1;
Test t2;
t1.print();
t2.print();
t1.setValue(20);
t2.print();
return 0;
}
类的静态成员
从命名空间的角度
类的静态成员只是类这个命名空间中的全局变量和全局函数。
不同之处是,类可以对静态成员进行访问权限的限制,而命名空间不可以的。
从面相对象的角度
类的静态成员函数属于类概念本身。
类的所有对象共享相同的静态成员。
通过一个简单示例看静态成员函数和普通成员函数的区别:
#include <stdio.h>
struct C1
{
int i;
int j;
short k;
short l;
};
class C2
{
int i;
int j;
short k;
short l;
};
/// class和struct,一个私有,一个公有,没有区别
struct C3
{
int i;
int j;
short k;
short l;
static int c;
public:
C3(){}
void print(){}
};
int main()
{
C1 c1;
C2 c2;
C3 c3;
printf("sizeof(c1)=%d\n",sizeof(c1));
printf("sizeof(c2)=%d\n",sizeof(c2));
printf("sizeof(c3)=%d\n",sizeof(c3));
return 0;
}
C++类中的成员函数和成员变量是分开存储的
*
成员变量
——普通成员变量:存储于对象中,与struct变量一样,有相同的内存布局和字节对齐方式。
*
成员函数
——存储于代码段中
静态成员与普通成员函数的区别
*
静态成员函数不包含指向具体对象的指针
*
普通成员函数包含一个指向具体对象的this指针。
小结:
C++类中可以包含属于类的静态成员。
静态成员变量在全局数据区分配空间。
静态成员函数不包含隐藏的this指针
通过类名可以直接访问静态成员。
通过对象名可以访问静态成员,所有的对象可以共享同一类静态成员。