#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;
}
找出这个程序的错误?
错误 1 error C2438: “height”: 无法通过构造函数初始化静态类数据
静态数据成员不能通过普通成员函数像普通数据成员那样赋值,需要通过类外单独赋值“int Box::height=2;”
#include <iostream>
#include <string>
using namespace std;
class Box
{
public:
Box(int w,int l):width(w),length(l){}
int volume( ){return height*width*length;};
private:
static int height; //静态的数据成员
int width;
int length;
};
int Box::height=2;
int main()
{
Box b(3,4);
cout<<"volume is "<<b.volume()<<endl;
return 0;
}