1、编写一个求立方体体积的函数volume,并编写main函数测试该函数;要求使用函数重载或者函数的参数带有默认值技术使得该函数至少有三种调用形式
2、改造上一题中的长方体类。长方体对象名为rectangle,数据成员包括:length,width,height;成员函数包括但不限定于:构造函数、析构函数、Set函数和GetVolume函数。编写main函数进行测试。
可使用构造函数重载、有默认参数、参数初始化列表、对象数组、对象指针、const关键字等。运用知识越多分值越高
代码如下,如有帮助,请采纳一下,谢谢。
题目1:
#include <iostream>
using namespace std;
class Lifangti
{
private:
double length;
public:
Lifangti(double l){length = l;}
float volume(float ll)
{
return ll * ll * ll;
}
int volume(int ll = 1)
{
return ll*ll*ll;
}
};
int main()
{
Lifangti ls(2);
cout << "边长为3的立方体体积=" << ls.volume(3) << endl;
cout << "边长为2.0的立方体体积=" << ls.volume((float)1.0) << endl;
cout << "边长为默认值的立方体体积为" << ls.volume() << endl;
}
题目2:
#include <iostream>
using namespace std;
class Rectangle
{
private:
int length;
int width;
int height;
public:
Rectangle(){}
Rectangle(int l,int w=1,int h=1){length = l;width = w;height = h;}
Rectangle( Rectangle &t)
{
Set(t.GetLeng(),t.GetWidth(),t.GetHeight());
}
~Rectangle(){}
void Set(int l,int w,int h){length = l;width = w;height = h;}
int GetLeng(){return length;}
int GetWidth(){return width;}
int GetHeight(){return height;}
int GetVolume(){return length * width * height;}
bool operator ==( Rectangle &r)const
{
if(this->length == r.GetLeng() && this->width == r.GetWidth() && this->height == r.GetHeight())
return true;
else
return false;
}
};
int main()
{
Rectangle* a[2];
a[0] = new Rectangle(1,2,3);
a[1] = new Rectangle();
a[1]->Set(2,2,2);
cout << "a[0]:" << a[0]->GetLeng() << "*" << a[0]->GetWidth() << "*" << a[0]->GetHeight()<< endl;
cout <<"其体积为" << a[0]->GetVolume() << endl;
cout << "a[1]:" << a[1]->GetLeng() << "*" << a[1]->GetWidth() << "*" << a[1]->GetHeight()<< endl;
cout <<"其体积为" << a[1]->GetVolume() << endl;
delete a[0];
delete a[1];
return 0;
}