C++ const的用法

本文总结C++语法中关键词const的所有用法。

函数重载中的用法

  1. 常成员函数和非常成员函数之间的重载
    首先先回忆一下常成员函数
    声明:<类型标志符>函数名(参数表)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
    
  2. 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重定义
    
  3. 形参为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;  
     }
     正常
    
  4. 形参为指针常量,但都是指向字符串变量

     #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重定义
    
  5. 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属性,而指示表示该指针不能指向其他地址。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值