本文总结C++语法中关键词const的所有用法。
函数重载中的用法
-
常成员函数和非常成员函数之间的重载
首先先回忆一下常成员函数
声明:<类型标志符>函数名(参数表)const;
说明:
(1)const是函数类型的一部分,在实现部分也要带该关键字。
(2)const关键字可以用于对重载函数的区分。
(3)常成员函数不能更新类的成员变量,也不能调用该类中没有用const修饰的成员函数,只能调用常成员函数。
(4)非常量对象也可以调用常成员函数,但是如果有重载的非常成员函数则会调用非常成员函数。#include<iostream> using namespace std; class TestConst { protected: int x; public: TestConst (int i):x(i) { } void fun() const { cout << "fun() const called " << endl; } void fun() { cout << "fun() called " << endl; } }; int main() { TestConst t1 (10); const TestConst t2 (20); t1.fun(); t2.fun(); return 0; } 输出结果: fun() called fun() const called
-
const修饰形参时的函数重载
#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; } 错误:函数fun重定义
-
形参为const指针
#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 = "hello world"; fun(ptr); return 0; } 正常
-
形参为指针常量,但都是指向字符串变量
#include<iostream> using namespace std; void fun(char *a) { cout << "non-const fun() " << a; } void fun(char* const a) { cout << "const fun() " << a; } int main() { const char *ptr = "hello world"; fun(ptr); return 0; } 错误:func重定义
-
const引用
#include<iostream> using namespace std; void fun(const int &i) { cout << "fun(const int &) called "<<endl; } void fun(int &i) { cout << "fun(int &) called "<<endl ; } int main() { const int i = 10; fun(i); return 0; } 正常
从以上内容来,const修饰形参时,普通形参不能实现重载,但当用于指针或引用时,由于改变了形参的const属性,所以可以实现函数重载,同时要注意char * const并没有改变形参的const属性,而指示表示该指针不能指向其他地址。