作业帮 > 综合 > 作业

定义一个Box(盒子)类,在该类定义中包括数据成员: length(长),width(宽)和height(

来源:学生作业帮 编辑:作业帮 分类:综合作业 时间:2024/05/09 20:03:00
定义一个Box(盒子)类,在该类定义中包括数据成员: length(长),width(宽)和height(

定义一个Box(盒子)类,在该类定义中包括数据成员: length(长)、width(宽)和height(高);成员函数: 构造函数Box,设置盒子长、宽和高三个初始数据;用函数volume 计算并输出盒子的体积.在main函数中,要求创建Box对象,并求盒子的体积.

int main()

{

       Box b1,b2(2,3,4);

       float v1,v2;

       v1 = b1.GetVolume();

       v2 = b2.GetVolume();

       if (v1>v2)

                   cout<<v1<<" "<<v2<<endl;

              else

                      cout<<v2<<" "<<v1<<endl;

       return 0;

}


#include <iostream>
using namespace std;

class Box {
\x09float length, width, height;
public:
\x09Box(float l, float w, float h);
\x09float GetVolume() const;
};

Box::Box(float l = 1, float w = 1, float h = 1) 
\x09: length(l), width(w), height(h) {}

float Box::GetVolume() const {
\x09return height * width * length;
}

int main()
{
\x09Box b1, b2(2, 3, 4);
\x09float v1, v2;
\x09v1 = b1.GetVolume();
\x09v2 = b2.GetVolume();
\x09if (v1>v2)
\x09\x09cout << v1 << " " << v2 << endl;
\x09else
\x09\x09cout << v2 << " " << v1 << endl;
\x09return 0;
}
再问: Box b1, b2(2, 3, 4);
这行有错哎~error C2512: 'Box' : no appropriate default constructor available
怎么改呢???
再答: #include <iostream>
using namespace std;

class Box {
\x09float length, width, height;
public:
\x09Box();
\x09Box(float l, float w, float h);
\x09float GetVolume() const;
};

Box::Box() : length(1), width(1), height(1) {}

Box::Box(float l, float w, float h)
: length(l), width(w), height(h) {}

float Box::GetVolume() const {
\x09return height * width * length;
}

int main()
{
\x09Box b1, b2(2, 3, 4);
\x09float v1, v2;
\x09v1 = b1.GetVolume();
\x09v2 = b2.GetVolume();
\x09if (v1>v2)
\x09\x09cout << v1 << " " << v2 << endl;
\x09else
\x09\x09cout << v2 << " " << v1 << endl;
\x09return 0;
}