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

王朝other·作者佚名  2006-01-09
宽屏版  字体: |||超大  

可以调用函数,而无需指定所有参数。 为了运行此函数,对于没有在函数调用中指定的参数,函数声明时参数必须有其默认值。

在下面的程序中,将看到如何实现带参数的函数。 给定长、宽和高,将使用此程序来计算盒子的体积。 体积将和长、宽、高一同显示。

#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函数时由始至终都必须为其赋值,就是因为在声明时没给他赋默认值

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有