静态数据成员

来源:百度知道 编辑:UC知道 时间:2024/05/22 04:36:32
#include<iostream.h>
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 a(15,20),b(20,30);
cout<<a.height<<endl;
cout<<b.height<<endl;
cout<<box::height<<endl;
cout<<a.volume()<<endl;
cout<<b.volume()<<endl;
return 0;
}
静态的数据成员是不是不能在构造函数里初始化?而必须单独在类外初始化?
为什么?

因为静态数据成员是属于类的,而不是专属于某个对象的。

初始化对象使用构造函数可以。但是静态成员必须要再类外完成定义。

明确的表示它是属于某个类的静态成员。是由所有对象共享共同来维护的。

是的。

是的.

不然不得报错啊