一,基本概念
1,静态成员变量是类所有,不依赖对象而存在,属于全局数据区。数据段
2,不能在类里面分配空间,只能在类外初始化,默认为0
3,可以通过类名直接访问public静态成员变量,也可以通过对象名,静态成员变量,也受访问权限限制
4,静态成员函数在不构造对象的情况下,可以直接访问静态成员,通过类名,但是普通成员函数就不行
5,用sizeof求对象的大小时,static成员变量不占空间,因为它属于类。求类大小也一样。
6,C++类对象中的成员变量和成员函数是分开存储的
成员变量
- 普通成员变量:存储于对象中,与struct变量有相同的内存布局和字节对齐方式
- 静态成员变量:存储于全局数据区中,不在对象中。
成员函数
- 存储于代码段中,所有对象共享
7,静态成员函数和非静态成员函数的
静态成员函数不包括指向当前对象的this指针
非静态成员函数包括指向当前对象的this指针
this指针的值是当前对象的起始地址。
test(int i){m=i;}其实等价于test(test* this,int i){this->m=i};
8,静态成员函数不能被const修饰。在用类名直接调用静态成员函数前提下,静态成员函数中只能调用静态成员变量。
二,应用
1,用来统计对象数目
#include <stdio.h>
class Test
{
private:
static int cCount;
public:
static int GetCount()
{
return cCount;
}
Test()
{
cCount++;
}
~Test()
{
cCount--;
}
};
int Test::cCount;
void run()
{
Test ta[100];
printf("Number of Object: %d\n", Test::GetCount());
}
int main()
{
Test t1;
Test t2;
printf("Number of Object: %d\n", Test::GetCount());
run();
printf("Number of Object: %d\n", Test::GetCount());
printf("Press any key to continue...");
getchar();
return 0;
}
2,单列模式
概念:一个类最多只能创建一个对象。
步骤:
- 把构造函数的访问级别设为private,使其在类外不能构造对象。
- 定义一个私有静态对象指针变量和一个公有静态成员函数
- 在静态成员函数中,判断那个静态对象指针是否为空,为空就new出一个对象,并返回。如果不为空,直接返回上次的对象指针。
3,代码
#include <cstdlib>
#include <iostream>
using namespace std;
class Singleton
{
private:
static Singleton* cInstance;
Singleton()
{
}
public:
static Singleton* GetInstance()
{
if( cInstance == NULL )
{
cout<<"new Singleton()"<<endl;
cInstance = new Singleton();
}
return cInstance;
}
void print()
{
cout<<"I'm Singleton!"<<endl;
}
};
Singleton* Singleton::cInstance = NULL;
void func()
{
Singleton* s = Singleton::GetInstance();
Singleton* s1 = Singleton::GetInstance();
Singleton* s2 = Singleton::GetInstance();
cout<<s<<" "<<s1<<" "<<s2<<endl;
s->print();
}
int main(int argc, char *argv[])
{
func();
cout << "Press the enter key to continue ...";
cin.get();
return EXIT_SUCCESS;
}