* 程序的版权和版本声明部分
* Copyright (c) 2011, 烟台大学计算机学院学生
* All rights reserved.
* 文件名称: class time
* 作 者: 于昊
* 完成日期: 2012 年 03 月 12 日
* 版 本 号: 1.0
* 对任务及求解方法的描述部分
* 输入描述:输入时间
* 问题描述:
* 程序输出:时间
* 问题分析:
* 算法设计:……
* /
#include <iostream> using namespace std; class Box { private: int length; int width; int height; public: int surface(); Box(int length =10,int width =10,int height =10); int volume(); void setdata(); }; Box::Box(int l,int w,int h):length(l),width(w),height(h){} int Box::volume() { return (length*width*height); } int Box::surface() { return 2*(length*width+length*height+width*height); } void Box::setdata() { cin>>length>>width>>height; } int main() { int i; Box b[5]={ Box(11,11,11), Box(22,22,22), Box(33,33,33), Box() }; b[4].setdata(); for(i=1;i<=5;i++) { cout<<"第"<<i<<"个立方体的体积是"<<b[i-1].volume()<<endl; cout<<"第"<<i<<"个立方体的表面积是"<<b[i-1].surface()<<endl; } return 0; }
Box b[5]={ Box(11,11,11), Box(22,22,22), Box(33,33,33), Box()这个地方第5个对象不用在大括号内定义,系统已经定义好 因为前面有Box[5]
只不过这个对象没有参数 所以只能在花括号外调用函数进行赋值。
Box::Box(int l,int w,int h):length(l),width(w),height(h){}这个相当于Box::Box(int l,int w,int h)
{
length=l;
width=w;
height=h;
}如果采用默认参数赋值,就必须有
Box(int length =10,int width =10,int height =10); 然后必须有Box::Box(int l,int w,int h)或 Box::Box(int l,int w,int h):length(l),width(w),height(h){}
而且与Box()不能共存,因为这是个构造函数,不默认参数。