1-3 函数重载与参数缺省

题目

Create a class that contains four member functions, with 0, 1, 2, and 3 int arguments, respectively. Create a main( ) that makes an object of your class and calls each of the member functions. Now modify the class so it has instead a single member function with all the arguments defaulted. Does this change your main( )?

代码

#include<iostream>
using namespace std;
class A 
{
	public:
		//void fun(){;}
		//void fun(int x1){a=x1;}
		//void fun(int x1,int x2){a=x1;b=x2;}
		void fun(int x1=0,int x2=0,int x3=0){a=x1;b=x2;c=x3;}
		void show()
		{cout << "a="<<a <<endl;
		cout << "b="<<b <<endl;
		cout << "c="<<c <<endl;}
	private:
		int a;int b;int c;
};
int main()
{
	A a1; a1.fun();
	a1.show();
	A a2; a2.fun(1);
	a2.show();
	A a3; a3.fun(1,2);
	a3.show();
	A a4; a4.fun(1,2,3);
	a4.show();
	return 0;
}

结果

函数重构结果:

参数缺省结果:

注意

  1. 函数重构:只跟 参数数量 与 参数类型 有关,与 函数返回类型 与 形参名字 无关
  2. 参数缺省:需要给参数默认值(如 x1 = 0;)
  • 11
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值