使用构造函数初始化成员数组

来源:互联网 发布:得不到的温柔网络歌手 编辑:程序博客网 时间:2024/05/18 09:17
#include <iostream>using namespace std;class Box//盒子类{public://定义一个构造函数用于初始化对象数组Box(int h, int w, int l);int volume();//计算盒子的体积private:int height;//盒子的高int width;//盒子的宽int length;//盒子的长};//定义一个构造函数用于初始化对象数组Box::Box(int h, int w, int l){height = h;width = w;length = l;}//计算盒子的体积int Box::volume(){int v = height * width * length;return v;}int main(){//使用构造函数初始化三个盒子Box a[3] = {Box(10,12,15),Box(15,18,20),Box(16,20,26),};//打印三个盒子的体积cout<<"volume of a[0] is "<<a[0].volume()<<endl;cout<<"volume of a[1] is "<<a[1].volume()<<endl;cout<<"volume of a[2] is "<<a[2].volume()<<endl;return 0;}


执行结果:


0 0
原创粉丝点击