1.静态数据成员的作用:它是类的不同对象的共享数据,它是全局变量的替代品!!
一个例子:
#include <iostream>
using namespace std;
/*
//错误初始化
class Box{
public:
Box(int h) : height(h){}
static int height;
};*/
//正确初始化
class Box{
public:
Box() {}
Box(int h) { height = 5;}//这句话初始化无效!!!!
static int height;
};
int Box::height = 10;//需要定义,不是声明!!!int 勿忘记,否则不能使用Box::height和a.height和b.height!!!
int main()
{
Box::height++;
cout << Box::height <<endl;
Box a;
a.height = 20;
cout << Box::height <<endl;
cout << a.height <<endl;
Box b;
b.height = 30;
cout << Box::height <<endl;
cout << a.height <<endl;
cout << b.height <<endl;
//Box::height和a.height和b.height是等价的
cout << "size = " <<sizeof(Box) <<endl; //size等于1
}
2.静态函数成员:没有this指针!不能直接使用非静态类成员,若要使用,则必须制定具体对象,而对静态成员,可以直接使用。
注意:
A对于静态函数成员,Box::volume()和box1.volume是等价的,这一点和静态数据成员一样!
B在静态函数成员中 ,由于没有this指针
cout << height <<endl;//合法
cout << width <<endl;//非法
cout << a.width <<endl;//合法
一个例子【静态数据成员+静态函数成员】
#include <iostream>
using namespace std;
class Student{
public:
Student(int n,int a,float s) :num(n),
age(a),score(s) {}
void total();
static float average();//静态函数
private:
int num;
int age;
float score;
static float sum;
static int count;
};
void Student::total()
{
sum += score;//score是自己的,sum是静态的
count ++; //count是静态的
}
float Student::average()//静态函数成员
{
return (sum /count);
}
float Student::sum = 0;
int Student::count = 0;
int main()
{
Student stud[3] = {
Student(1001,18,70),
Student(1002,19,78),
Student(1005,20,98),
};
for(int i = 0; i < 3; i++)
stud[i].total();
cout << "average = " << Student::average() <<endl;
return 0;
}