1、把数据成员定义成静态
以关键字static开头
class Box
{
public:
int volumw();
private:
static int height;//把height定义为静态的数据成员
int width;
int length;
};
作用:
希望同类的各对象中的数据成员的值都是一样的,就可以把它定义为静态数据成员,这样它就可以为各对象所共有,而不只属于某个对象成员,所有对象都可以引用它。
静态数据成员只在内存中占一份空间。
一个类中可以由一个或多个静态数据成员,所有对象都共享这些静态数据成员,都可以引用它。
公用的静态数据成员可以初始化,但只能在类外进行初始化。
例:
int Box::height=10;//表示对Box类中的数据成员初始化
一般形式为:
数据类型 类名::静态数据成员名=初值;
只有在类体声明静态数据成员时加static,不必再初始化语句中加static。
注意:
不能用构造函数的参数初始化表对静态数据成员初始化。
eg:以下是错误例子:
Box(int h,int w,int len):height(h){}//错误,height是静态数据成员。
利用静态数据成员:
#include <iostream>
using namespace std;
class Box
{
public:
Box (int,int);
int volume();
static int height;//把height定义为公用的静态的数据成员
int width;
int length;
};
Box::Box(int w,int len)//对构造函数对width和length赋初值
{
width=w;
length=len;
}
int Box::volume()
{
return(height*width*length);
}
int Box::height=10;//对公用静态数据成员height进行初始化
int main()
{
Box a(15,20),b(20,30);
cout<<a.height<<endl;
cout<<b.height<<endl;
cout<<Box::heigth<<endl;
cout<<a.volume()<<endl;
return 0;
}
输出结果为:
如果静态数据名被定义为私有的,则不能在类外直接引用,而必须通过公用的函数引用。
用静态成员函数访问静态数据成员
定义:
成员函数也可以定义为静态的,在类中声明函数的前面static就成为了静态成员函数。
static int volume();
静态成员函数是类的一部分而不是对象的一部分。如果在类外调用公用的静态成员函数,要用类名和域运算符“::”。
Box::volume();
允许通过对象名调用静态成员函数:
a.volume();
解释:
非静态成语函数有this指针,而静态成员函数没有this指针。由此决定了静态成员函数不能访问非静态成员。
整体例子:
#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;//静态成员sum
static int count;//静态成员count
};
void Student::total()
{
sum+=score;
count++;
}
float Student::average()
{
return(sum/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(1003,20,98}
};
int n;
cout<<"please input the number of students:";
cin>>n;
for(int i=0;i<n;i++)
stud[i].total();
cout<<"the average score of"<<n<<"student is"<<Student::average()<<endl;
return 0;
}
公用成员函数可以引用本对象中的一般成员函数(非静态数据成员),也可以引用类中的静态数据成员。