关键字 static 可以用于说明一个类的成员,静态成员提供了一个同类对象的共享机制:
- 把一个类的成员说明为 static 时,这个类无论有多少个对象被创建,这些对象共享这个 static 成员
- 静态成员局部于类,它不是对象成员
静态成员函数数冠以关键字static:
- 静态成员函数提供不依赖于类数据结构的共同操作,它没有this指针
- 在类外调用静态成员函数用 “类名 :: ”作限定词,或通过对象调用
- 静态函数中 不能使用 普通成员变量 普通成员函数
静态成员变量和函数的语法:
#include<iostream>
using namespace std;
class B
{
public :
void printC()
{
cout << "c=" << c << endl;
}
void AddC()
{
c++;
}
static void getC()
{
cout << "c=" << c << endl;
//cout << "b=" << b << endl;
}
private:
int a;
int b;
static int c;
protected:
};
int B::c = 10;
void main9()
{
B b1, b2, b3;
b1.printC();
b2.AddC();
b2.printC();
b3.printC();
//静态成员函数调用的两种格式
//静态函数中 不能使用 普通成员变量 普通成员函数 ..
b3.getC();
B::getC();
system("pause");
}