1创建类Block用来描述长方体,私有数据成员length、width、height记录长方体的长、宽、高。要求用成员函数实现以下功能:
①成员函数input用来从键盘分别输入长方柱的长、宽、高;
②成员函数volume计算长方柱的体积;
③成员函数output输出长方柱的体积。
最后为Block类建立构造函数用于初始化,其中包括无参数构造函数,有参数构造函数,拷贝构造函数。
#include<iostream>
using namespace std;
class Block //定义类
{
public:
Block() {}; //无参数构造函数初始化
Block(float l, float w, float h) :length(l), width(w), heigth(h) {} //有参数构造函数初始化
Block(const Block&other) { //拷贝构造函数初始化
length = other.length; width = other.width; heigth = other.heigth;
cout << "The copy constructor has been called!" << endl;
}
void input();
float volume();
void output();
private:
float length, width, heigth; //定义三种数据成员
};
int main()
{ //定义三个长方体对象分别验证三种数据成员初始化
Block cuboid;
cuboid.input();
cuboid.output();
Block cuboid1(10, 10, 10);
cuboid1.output();
Block cuboid2(cuboid);
cuboid2.output();
return 0;
}
void Block::input() //在类外定义成员函数
{
cout << "Please enter the length,width and heigth of the cube :" << endl;
cin >> length;
cin >> width;
cin >> heigth;
}
float Block::volume()
{
return length * width*heigth;
}
void Block::output()
{
cout << "The volume of the cuboid is : " <<volume() << endl;
}