本文共 1804 字,大约阅读时间需要 6 分钟。
目录
#includeusing 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这两个成员函数‘void fun() const’和‘void fun()’有着相同的函数名,返回值以及参数列表,只是一个带有const另一个没有。
另外,如果仔细观察下输出,会发现 ‘const void fun()’函数是由一个const对象调用的,而‘void fun()’函数是由一个非const对象调用。 C++允许成员方法基于基本的const类型来进行重载。基于const类型的重载,在函数返回引用或指针的情况下是有用的。我们可以构造一个const函数,然后返回一个const引用或const指针;或者构造一个非const函数,返回非const引用或指针。//例子1,会编译失败#includeusing 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;}
输出:
Compiler Error: redefinition of 'void fun(int)'//例子2,运行正常#includeusing 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 = "hello world"; fun(ptr); return 0;}
输出:const fun() hello world
#includeusing 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;}
输出:
fun(const int &) called转载地址:http://hmeji.baihongyu.com/