C++允许类的成员函数基于const重载。
#include<iostream>
using namespace std;
class Test
{
protected:
int x;
public:
Test (int i):x(i) { }
void fun() const
{
cout << "fun() const called " << endl;
}
void fun()
{
cout << "fun() called " << endl;
}
};
int main()
{
Test t1 (10);
const Test t2 (20);
t1.fun();
t2.fun();
return 0;
}
输出:
fun() called fun() const called我们可以看到非const对象调用的是非const成员函数,const对象调用的是const成员函数。
下面两个例子很有意思,重载不是类的成员函数,而是普通函数的重载,
程序1
#include<iostream>
using namespace std;
void fun(const int i)
{
cout << "fun(const int) called ";
}
void fun(int i)
{
cout << "fun(int ) called " ;
}
int main()
{
const int i = 10;
fun(i);
return 0;
}
输出:
编译错误!
error C2084: 函数“void fun(const int)”已有主体
error C3861: “fun”: 找不到标识符
#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 = "CSDN";
fun(ptr);
return 0;
}
输出:
const fun() CSDN