调用带默认参数的函数示例

可以调用函数,而无需指定所有参数。 为了运行此函数,对于没有在函数调用中指定的参数,函数声明时参数必须有其默认值。
在下面的程序中,将看到如何实现带参数的函数。 给定长、宽和高,将使用此程序来计算盒子的体积。 体积将和长、宽、高一同显示。

#include<iostream.h>

class Box
{
  private:
    int length;
    int width;
    int height;
  public:
    int get_volume(int lth,int wdth = 2,int ht = 3); //注意:这里的第一个参数并没有赋值
};

int Box::get_volume(int l, int w, int h)
{
  length = l;
  width = w;
  height = h;
  cout<< length<<'/t'<< width<<'/t'<< height<<'/t';
  return length * width * height;
}

void main()
{
  Box cuboid;
  int x = 10, y = 12, z = 15;
  cout <<"Length Width Height Volume/n";
  cout << cuboid.get_volume(x, y, z) << "/n";
  cout << cuboid.get_volume(x, y) << "/n";
  cout << cuboid.get_volume(x) << "/n";
  cout << cuboid.get_volume(x, 7) << "/n";
  cout << cuboid.get_volume(5, 5, 5) << "/n";
}

int Box::get_volume(int l, int w, int h)
{
  length = l;
  width = w;
  height = h;
  cout<< length<<'/t'<< width<<'/t'<< height<<'/t';
  return length * width * height;
}

void main()
{
  Box cuboid;
  int x = 10, y = 12, z = 15;
  cout <<"Length Width Height Volume/n";
  cout << cuboid.get_volume(x, y, z) << "/n";
  cout << cuboid.get_volume(x, y) << "/n";
  cout << cuboid.get_volume(x) << "/n";
  cout << cuboid.get_volume(x, 7) << "/n";
  cout << cuboid.get_volume(5, 5, 5) << "/n";
}

输出:

Length Width Height Volume

10 12 15 1800

10 12   3   360

10   2   3    60

10   7   3   210

  5   5   5  125

说明:在程序的结果中不难总结出参数wdth和ht在调用get_volume函数时如果不给他们赋值的话将会调用声明时的默认值;而lth在调用get_volumelth函数时由始至终都必须为其赋值,就是因为在声明时没给他赋默认值

  5   5   5  125

说明:在程序的结果中不难总结出参数wdth和ht在调用get_volume函数时如果不给他们赋值的话将会调用声明时的默认值;而lth在调用get_volumelth函数时由始至终都必须为其赋值,就是因为在声明时没给他赋默认值

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值