static 数据类型 静态数据成员名;
例如:
static int total;
类名::静态数据成员名=初始值;
例如:
int Student::total=0;
!定义一个矩形类Rectangle,实现算法、显示矩形面积和统计矩形个数的功能。
#include<iostream>
using namespace std;
class Rectange{
public:
Rectange(int =0,int =0);
void Show();
int Area();
static int count;
private:
int length;
int width;
} ;
int Rectange::count=0;
Rectange::Rectange(int 1,int w):length(1),width(w){
count++;
}
int Rectange::Area(){
return (length * width);
}
void Rectange::Show(){
cout<<"length"<<length<<" ";
cout<<"width"<<width<<" ";
cout<<"Area"<<Area()<<endl;
}
int main(){
Rectange rect1(3,3);
rect1.Show();
cout<<"count="<<Rectange::count<<endl;
Rectange rect2(3,7);
rect2.Show();
cout<<"count="<<Rectange::count<<endl;
Rectange rect3(5,5);
rect3.Show();
cout<<"count="<<rect3.count<<endl;
return 0;
}