2013第七周上机任务【阅读程序并改错】

来源:互联网 发布:php 截取第一个字符串 编辑:程序博客网 时间:2024/05/17 02:25

原程序:

#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;}


 

运行结果:

原创粉丝点击