geeksforgeeks 010-函数重载和const

预测下列程序的输出

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
#include<iostream>
using namespace std;

class Test
{
protected:
int x;
public:
Test (int i):x(i) { }
void () const
{

cout << "fun() const called " << endl;
}
void ()
{

cout << "fun() called " << endl;
}
};

int main()
{
Test t1 (10);
const Test t2 (20);
t1.fun();
t2.fun();
return 0;
}

Output

1
2
fun() called
() const called

当函数返回指针或引用时,对const类型的函数进行重载将会十分有用。

如果参数带有const,会怎样

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

#include<iostream>
using namespace std;

void (const int i)
{
cout << "fun(const int) called ";
}
void (int i)
{
cout << "fun(int ) called " ;
}
int main()
{
const int i = 10;
fun(i);
return 0;
}

Output:

1
Compiler Error: redefinition of 'void fun(int)'


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// PROGRAM 2 (Compiles and runs fine)
#include<iostream>
using namespace std;

void fun(char *a)
{
cout << "non-const fun() " << a;
}

void fun(const char *a)
{
cout << "const fun() " << a;
}

int main()
{
const char *ptr = "GeeksforGeeks";
fun(ptr);
return 0;
}

Output:

1
const fun() GeeksforGeeks

只有在const参数是指针或引用的情况下,函数重载才有效