函数声明的时候可以只写参数类型,不写参数名
当函数的参数缺省的时候,如果给函数传递参数,则函数的参数为传进来的数,否则
函数的参数为默认值
函数参数缺省和函数重载的使用有几分相像,但是不同:
具有默认参数的函数重载的是参数的数值,而重载函数重载的是参数的类型。
1:普通函数参数的缺省
#include <iostream> using namespace std; void fun(int n = 0, int m = 0) { cout << "n:" << n << " m:" << m << endl; } int main() { fun(); //输出默认参数0 0 fun(1,2);//输出参数1, 2 return 0; }
2:类中方法的参数缺省
#include <iostream> using namespace std; class A { public: void set(int = 50, int = 3); void count(bool = false); private: int w; int h; }; void A::set(int width, int height) { w = width; h = height; } void A::count(bool val) { if(val) cout << "val的值为真时:" << w*h << endl; else cout << "val的值为假时:" << w*h/2 << endl; } int main() { A a; a.set(); a.count(); a.count(true); a.set(100,55); a.count(); a.count(true); return 0; }
不仅普通函数可以重载,构造函数也可以重载:
/*构造函数也可以重载*/ #include <iostream> using namespace std; class rectangle { public: rectangle(){cout << "构建一个长方形\n";} rectangle(int l, int w){ length = l; width = w; cout << "长方形的面积为:" << length*width << endl;} rectangle(int l, int w, int h){length = l; width = w; height = h; cout << "长方体的体积为:" << l*w*h << endl;} private: int length; int width; int height; }; int main() { rectangle(); rectangle(100, 233); rectangle(4, 5, 6); return 0; }
原文:http://www.cnblogs.com/rain-1/p/4873218.html