原程序:
#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中对其进行了初始化。静态数据成员不能通过构造函数初始化。
改正:
#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:
int height; //非静态的数据成员
int width;
int length;
};
int main()
{
Box b(2,3,4);
cout<<"volume is "<<b.volume()<<endl;
system("PAUSE");
return 0;
}
运行结果: