1.格式就是:直接写类型,不命名。
void fun(int a,int){
}
int main(){
fun(10,10);//有占位参数的时候(此时未设置默认参数)必须传递同类型的数值,否则报错。
}
2.加上默认参数之后再调用就不用传参数。
void fun(int a,int =10){
}
int main(){
fun(10);//有占位参数,也有默认参数,这时候就不要传值就行。
}
应用示例:以一个前置和后置++的重载为例(前置和后置指的是++号的前后位置)
#include <iostream>
using namespace std;
class clock {
public:
int hour;
int minute;
int second;
clock(int hour, int minute, int second) {
if (hour >= 0 && hour <= 24 && minute >= 0 && minute <= 60 && second >= 0 && second <= 60) {
this->hour = hour;
this->minute = minute;
this->second = second;
}
else
cout << "time error" << endl;
}
void showtime() {
cout << hour << ":" << minute << ":" << second << ":" << endl;
}
clock &operator ++() {
second++;
if (second >= 60) {
second -= 60;
minute++;
if (minute >= 60) {
minute -= 60;
hour=(hour+1)%24;
}
}
return *this;
}
clock operator ++(int) { //这段代码很直观形象的说明了为什么后置++和cout连用的时候会输出原值的问题。
clock old=*this;
++(*this);
return old; //返回传进来的值,这并没有写错。而且因为返回的是临时对象,所有不能使用引用返回&
}
};
int main() {
clock myclock(23,59,59);
myclock.showtime();
(myclock++).showtime();
(++myclock).showtime();
return 0;
}
结果:
可以看出,第一次递增后并没有输出0:0:0,而是输出的原值23:59:59 这就很符合前置和后置++的区别