原程序:
#include <iostream>
#include <string>
using namespace std;
class Box
{
public:
Box(int h,int w,int l):height(h),width(w),length(l){}
int volume( ){return height*width*length;};
private:
static int height; //静态的数据成员
int width;
int length;
};
int main()
{
Box b(2,3,4);
cout<<"volume is "<<b.volume()<<endl;
return 0;
}
上面这个程序会出现错误,因为定义数据成员时将height定义成了静态数据成员,在定义构造函数Box时又将数据成员height进行初始化,所以会出现错误。
修改后的程序:
#include<iostream>
#include<string>
using namespace std;
class Box{
public:
Box(int ,int );//定义构造函数时不能对height进行初始化
int volume(){return height*width*length;};
private:
static int height;//静态的数据成员
//这里将height定义成了静态的数据成员,所以上面定义构造函数时不能对height进行初始化
int width;
int length;
};
Box::Box(int w,int l){
width=w;
length=l;
}
int Box::height=2;//表示对Box类中的数据成员初始化
int main(){
Box b(3,4);
cout<<"volume is "<<b.volume()<<endl;
return 0;
}
运行结果: