C++基础-类的认识和初始化

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;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值