引言:
结构化(即模块化)程序设计中,基本单位是函数,模块间对数据的共享方式只有两种①函数与函数之间的参数传递;②全局变量。
面向对象中,兼顾数据的共享和保护①public:在类的内部,成员函数可以访问任何数据和函数;②private::在类的外部,类的私有成员数据一切隐藏。
然而,同一个类的对象与对象之间也需要数据和函数的共享,静态的成员数据和成员函数便是该类的属性,而不属于任何的实例对象。这是static关键字的由来。
1.静态数据成员
源程序:
#include "stdafx.h"
#include<iostream>
using namespace std;
//定义类
class Point{
private:
int x,y;
static int count;//定义静态成员数据
public:
Point(int x=0,int y=0):x(x),y(y){
count++;
}
Point(Point &p){
x=p.x;
y=p.y;
count++;
}
int getX(){ return x;}
int getY(){ return y;}
void showCount(){
cout<<"count="<<count;
}
};
int Point::count=0;//定义(第二次定义!)静态成员数据,并初始化
//主函数
int _tmain(int argc, _TCHAR* argv[])
{
//定义一个对象a
Point a(4,5);
cout<<"Point A:"<<a.getX()<<","<<a.getY()<<endl;
a.showCount();
//定义一个对象b
Point b(a);
cout<<"Point B:"<<b.getX()<<","<<b.getY()<<endl;
b.showCount();
return 0;
}
【注意】
静态成员数据声明和初始化的方式(是在类外通过类名直接进行访问并初始化!)。
2.静态成员函数
源程序:
#include "stdafx.h"
#include<iostream>
using namespace std;
//定义类
class Point{
private:
int x,y;
static int count;//定义静态成员数据
public:
Point(int x=0,int y=0):x(x),y(y){
count++;
}
Point(Point &p){
x=p.x;
y=p.y;
count++;
}
int getX(){ return x;}
int getY(){ return y;}
static void showCount(){
cout<<"count="<<count;
}
};
int Point::count=0;//定义(第二次定义!)静态成员数据,并初始化
//主函数
int _tmain(int argc, _TCHAR* argv[])
{
Point::showCount();//对于静态成员函数,可以通过类名来访问(这就体现静态数据和函数是该类本身的属性,而不属于任何对象)
//定义一个对象a
Point a(4,5);
cout<<"Point A:"<<a.getX()<<","<<a.getY()<<endl;
Point::showCount();
//定义一个对象b
Point b(a);
cout<<"Point B:"<<b.getX()<<","<<b.getY()<<endl;
Point::showCount();
return 0;
}
【注】
非静态成员函数:只能通过对象来访问;
静态成员函数:可以通过类名和对象访问(但一般使用类名直接访问)。
3.静态成员函数与静态成员数据
class A{
public:
static void func(A a);
private:
int x;
};
void A::func(A a){
cout<<x;//非法
cout<<a.x;
}
【注意】
静态成员函数:可以直接访问静态成员数据和成员函数;
如果访问非……,只能通过对象引用。