1)后置声明函数默认参数来简化系统库。
externtime_ttime(time_t*=nullptr); intmain() { std::cout<<time() <<std::endl; // usuallystd::cout<<time(nullptr) <<std::endl; return0; }
2)声明单个默认参数
usingnamespacestd; voidshow_point(intx, inty, intz) { cout<<x<<" "<<y<<" "<<z<<endl; } externvoidshow_point(intx, inty, intz=0); externvoidshow_point(intx, inty=0, intz); externvoidshow_point(intx=0, inty, intz); intmain() { show_point(1, 2, 3); show_point(1); show_point(1, 2); return0; }
3)来看下虚函数的默认参数
usingnamespacestd; classA{ public: virtualvoidrun(intx=0) { cout<<"this is A x="<<x<<endl; } virtualvoidrun_x0() { run(); } virtual~A() =default; }; classB : publicA{ public: virtualvoidrun(intx=1) override { cout<<"this is B x="<<x<<endl; } }; intmain() { Bb; B*pb=&b; A*pa=pb; pb->run(); // this is B x=1pa->run(); // this is B x=0 (用A的默认参数调用了B的run)pb->run_x0(); // this is B x=0 (同pa->run())pa->run_x0(); // this is B x=0 (同pa->run())return0; }