题目
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;
}
结果
函数重构结果:
参数缺省结果:
注意
- 函数重构:只跟 参数数量 与 参数类型 有关,与 函数返回类型 与 形参名字 无关
- 参数缺省:需要给参数默认值(如 x1 = 0;)