C++ 静态成员
时间:2010-11-14 来源:luozhiyong131
/************
静态数据成员
**************/
#include <iostream.h>
class Worker
{
private:
char *name;
int worktime;
public:
static int total;
void workTime(int n);
};
void Worker::workTime(int n)
{
worktime=n;
total+=n;
}
int Worker::total = 0;
void main()
{
Worker w1,w2,w3;
w1.workTime(48);
w2.workTime(36);
w3.workTime(40);
cout<<"Total = "<<Worker::total<<endl;
}
/********
数据共享
**********/
#include <iostream.h>
class Test
{
private:
int m;
public:
static int n;
Test(int mm){ m=mm; n++; }
void Display();
};
void Test::Display()
{
cout<<"n = "<<n<<"\tm = "<<m<<endl;
}
int Test::n=0;
void main()
{
Test t1(10);
t1.Display();
Test t2(20);
t2.Display();
Test::n++;
t2.Display();
}
/**********
静态成员函数
***********/
#include <iostream.h>
class Preson
{
private:
char name[20];
static int ID;
public:
static int number();
};
int Preson::number()
{
return ID;
}
int Preson::ID = 1001;
void main()
{
Preson p1;
cout<<"类名引用:"<<Preson::number()<<endl;
cout<<"对像引用:"<<p1.number()<<endl;
}
/****************************
静态成员函数引用非静态数据成员
******************************/
#include <iostream.h>
class Myclass
{
private:
int m;
static int n;
public:
Myclass();
static int getn(Myclass a);
};
Myclass::Myclass()
{ m = 10; }
int Myclass::getn(Myclass a)
{
cout<<a.m<<endl;
return n;
}
int Myclass::n = 100;
void main()
{
Myclass ap;
cout<<ap.getn(ap)<<endl;
cout<<Myclass::getn(ap)<<endl;
}
/****************************
静态成员函数和一般成员函数
******************************/
#include <iostream.h>
class point
{
private:
long x,y;
static long countP;
public:
static long colorID;
point(long xx=0,long yy=0) { x=xx; y=yy; countP++; }
point(point & p);
long getx() { return x; }
long gety() { return x; }
static void getcntp() { cout<<"Points Number is: "<<countP<<endl; }
};
point::point(point & p)
{
x=p.x; y=p.y; countP++;
}
long point::countP = 0;
long point::colorID = 0;
void main()
{
point::getcntp();
point p1(4,5);
cout<<"point p1: ("<<p1.getx()<<","<<p1.gety()<<")"<<endl;
p1.getcntp();
cout<<"point color(p1) "<<p1.colorID<<endl;
point p2(4,5);
cout<<"point p2: ("<<p2.getx()<<","<<p2.gety()<<")"<<endl;
p2.getcntp();
cout<<"point color(p2) "<<p2.colorID<<endl;
}