C++ const函数返回值必须为const引用

本文探讨了C++中类成员操作符重载时返回类型的常量性问题,通过对比正确的编译代码与错误的编译代码,解释了为何在实现类成员[]操作符时需要将其声明为返回const引用,以防止对返回的对象进行修改。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

编译正确代码:

[html]  view plain  copy
 print ?
  1. #include<stdio.h>  
  2. #include <string.h>  
  3. #include<iostream>  
  4. using namespace std;  
  5.   
  6. class T{  
  7.     public:  
  8.         T(string p)  
  9.         {  
  10.             ptext = p;  
  11.         }  
  12.         const char & operator [](int pos) const  
  13.         {  
  14.             return ptext[pos];  
  15.         }  
  16.         string ptext;  
  17. };  
  18. int main()  
  19. {  
  20.     string s = "abcd";  
  21.     T t(s);  
  22.     //t[0] = 't';//因为为const返回类型,所以不能赋值  
  23.     printf("%s\n", s.c_str());  
  24. }  

编译错误代码:

[html]  view plain  copy
 print ?
  1. #include<stdio.h>  
  2. #include <string.h>  
  3. #include<iostream>  
  4. using namespace std;  
  5.   
  6. class T{  
  7.     public:  
  8.         T(string p)  
  9.         {  
  10.             ptext = p;  
  11.         }  
  12.         char & operator [](int pos) const//返回类型不为const编译错误  
  13.         {  
  14.             return ptext[pos];  
  15.         }  
  16.         string ptext;  
  17. };  
  18. int main()  
  19. {  
  20.     string s = "abcd";  
  21.     T t(s);  
  22.     //t[0] = 't';//因为为const返回类型,所以不能赋值  
  23.     printf("%s\n", s.c_str());  
  24. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值