一、静态数据成员
#include <iostream>
using namespace std;
class Box
{
public:
Box(int, int);
int volume();
static int height;
int width;
int length;
};
Box::Box(int w, int len)
{
width= w;
length= len;
}
int Box::volume()
{
return (height * width * length);
}
int Box::height= 10;
int main()
{
Box b1(15, 20), b2(2, 3);
cout << "b1的高度为" << b1.height << endl;
cout << "b2的高度为" << b2.height << endl;
cout << "b1的体积为" << b1.volume() << endl;
cout << "b2的体积为" << b2.volume() << endl;
return 0;
}

二、静态函数
#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;
count++;
}
float Student::average()
{
return (sum/count);
}
float Student::sum= 0;
int Student::count= 0;
int main()
{
Student stud[3]={
Student(1001, 11, 70),
Student(1002, 12, 80),
Student(1003, 13, 90)
};
int n;
cout << "请输入学生数量:" << endl;
cin >> n;
for(int i=0; i<n; i++)
{
stud[i].total();
}
cout << n << "个学生的平均分为:" << Student::average() << endl;
return 0;
}
