Skip to content

函数重载

在同一个作用域内,可以声明几个功能类似的同名函数,但是这些同名函数的形式参数(指参数的个数、类型或者顺序)必须不同。

c
#include <cstdio>

int Max(int a,int b){
    if( a < b) return b;
    return a;
}

int Max(int a,int b,int c){
    if( a < b) a = b;
    if( a < c) a = c;
    return a;
}

int main(){
    printf("%d\n",Max(1,2));
    printf("%d\n",Max(1,2,3));
    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

重载运算符

重载的运算符是带有特殊名称的函数,函数名是由关键字 operator 和其后要重载的运算符符号构成的。与其他函数一样,重载运算符有一个返回类型和一个参数列表。

例子:重载+

c
#include <cstdio>
#include <cstdio>
#include <iostream>
using namespace std; 

struct Saiyan {
    int val;
    string name;
    Saiyan(){}
    Saiyan(string name,int val):name(name),val(val){}
    Saiyan operator+(Saiyan a){ //内部重载
        Saiyan c;
        c.val = val + a.val;
        c.name = name+a.name;
        return c;
    }
};

////全局重载
//Saiyan operator+(Saiyan a,Saiyan b){
    //Saiyan c;
    //c.val = a.val + b.val;
    //c.name = a.name+b.name;
    //return c;
//}

int main(){
    Saiyan a("a",100);
    Saiyan b("b",110);
    Saiyan c = a + b;
    cout << "Saiyan c : " << endl;
    cout << "  val : " << c.val << endl;
    cout << "  name: " << c.name<< endl;
    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

重载<

一个排序的例子

c
#include <cstdio>
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std; 

struct node {
    int x,y;
    bool operator <(node b){
        if( x != b.x) return x< b.x;
        return y < b.y;
    }
};
node a[3];
int main(){
    int i;
    a[0] = {2,3};
    a[1] = {2,2};
    a[2] = {1,2};
    sort(a,a+2+1);
    for(i=0;i<=2;++i){
        printf("%d %d\n",a[i].x,a[i].y);
    }
    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

重载[]

返回对象内的数组内容

c
#include <cstdio>
#include <cstdio>
#include <iostream>
using namespace std; 

struct S {
    int a[10];
    int & operator[](int i){
        return a[i];
    }
};
int main(){
    S s;
    int i;
    for(i=0;i<=9;++i) s[i] = i;
    for(i=0;i<=9;++i){
        printf("%d ",s[i]);
    }
    printf("\n");
    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

下面是可重载的运算符列表:

|----------------|-----------------------------------------------------------------------| | 双目算术运算符 | + (加),-(减),(乘),/(除),% (取模) | | 关系运算符 | ==(等于),!= (不等于),< (小于),> (大于>,<=(小于等于),>=(大于等于) | | 逻辑运算符 | (逻辑或),&&(逻辑与),!(逻辑非) | | 单目运算符 | + (正),-(负),(指针),&(取地址) | | 自增自减运算符 | ++(自增),--(自减) | | 位运算符 | (按位或),& (按位与),~(按位取反),^(按位异或),,<< (左移),>>(右移) | | 赋值运算符 | =, +=, -=, *=, /= , % = , &=, =, ^=, <<=, >>= | | 空间申请与释放 | new, delete, new[ ] , delete[] | | 其他运算符 | ()(函数调用),->(成员访问),,(逗号),[](下标) |

下面是不可重载的运算符列表: |---------|--------------------| | 成员访问运算符 | . | | 成员指针访问运算符 | .*, ->* | | 域运算符 | :: | | 长度运算符 | sizeof | | 条件运算符 | ?: | | 预处理符号 | # |

参考/引用