C++构造类函数计算长方体体积

先创建一个类,再在里面构造函数

class Cuboid//创建长方体类
{
private://定义了三个私有变量
	double length;//长
	double width;//宽
	double height;//高
public:
	double getCu()
	{
		return length, width, height;//返回长宽高
	}
	void setCu(double length, double width, double height)//函数获取参数
	{
		this->length = length;
		this->width = width;
		this->height = height;
		cout << endl;
	}
	double calCuV(double length, double width, double height)
	{
		double cal = length * width*height;
		cout << "长方体的体积V是:" << cal;
		cout << endl;
		return cal;//返回值是体积底面积*高
	}
	//构造函数
	//01.无参
	Cuboid() { double length = 0; double width = 0; double height=0;}
	//02.有参
	Cuboid(double length, double width, double height)
	{
		this->length = length;
		this->width = width;
		this->height = height;
	}
	Cuboid(Cuboid&c)
	{
		this->length = c.height;
		this->width = c.width;
		this->height = c.width;
	}
};

函数内容细化放在类里面比较明了简洁也可以放在类外面创建类函数

创建用户输入的变量

    double L = 0;
	double W = 0;
	double H = 0;

	cout << "请输入长方体的底部长L:";
	cin >> L;
	cout << endl;
	cout << "请输入长方体的底部宽W:";
	cin >> W;
	cout << endl;
	cout << "请输入长方体的整体高H:";
	cin >> H;
	cout << endl;
    //写在main函数中

创建类变量,调用类里面定义好的函数

    Cuboid cu1;
	cu1.setCu(L, W, H);
	int calV1 = cu1.calCuV(L, W, H);
	cout << "------**------" << endl;

	Cuboid cu2(2*L,2*W,2*H);
	int calV2 = cu2.calCuV(L, W, H);
	cout << "------**------" << endl;

	Cuboid cu3(cu1);
	int calV3 = cu3.calCuV(L, W, H);
	cout << "------**------" << endl;

接下来用头文件,命名空间,函数体等连接起所有代码

请欣赏

//2、计算长方体的体积,通过设计类来实现。数据成员包括length(长)、width(宽)、height(高)。
//要求:至少求三个长方体的体积
#include
using namespace std;

class Cuboid//创建长方体类
{
private://定义了三个私有变量
	double length;//长
	double width;//宽
	double height;//高
public:
	double getCu()
	{
		return length, width, height;//返回长宽高
	}
	void setCu(double length, double width, double height)//函数获取参数
	{
		this->length = length;
		this->width = width;
		this->height = height;
		cout << endl;
	}
	double calCuV(double length, double width, double height)
	{
		double cal = length * width*height;
		cout << "长方体的体积V是:" << cal;
		cout << endl;
		return cal;//返回值是体积底面积*高
	}
	//构造函数
	//01.无参
	Cuboid() { double length = 0; double width = 0; double height=0;}
	//02.有参
	Cuboid(double length, double width, double height)
	{
		this->length = length;
		this->width = width;
		this->height = height;
	}
	Cuboid(Cuboid&c)
	{
		this->length = c.height;
		this->width = c.width;
		this->height = c.width;
	}
};

int main()
{
	double L = 0;
	double W = 0;
	double H = 0;

	cout << "请输入长方体的底部长L:";
	cin >> L;
	cout << endl;
	cout << "请输入长方体的底部宽W:";
	cin >> W;
	cout << endl;
	cout << "请输入长方体的整体高H:";
	cin >> H;
	cout << endl;

	Cuboid cu1;
	cu1.setCu(L, W, H);
	int calV1 = cu1.calCuV(L, W, H);
	cout << "------**------" << endl;

	Cuboid cu2(2*L,2*W,2*H);
	int calV2 = cu2.calCuV(L, W, H);
	cout << "------**------" << endl;

	Cuboid cu3(cu1);
	int calV3 = cu3.calCuV(L, W, H);
	cout << "------**------" << endl;

	system("pause");
	return 0;
}

你可能感兴趣的:(C++,小白,c++,java,开发语言)