C++中const重载

来源:互联网 发布:sql where语句 1,4 编辑:程序博客网 时间:2024/05/01 07:46

转自:http://blog.csdn.net/sulliy/article/details/5643443

众所周知,C++实现函数重载有两种情况:函数参数的类型不同,参数的个数不同。而与函数的返回值没有什么关系。

需要注意的是在如下情况下:

[c-sharp] view plaincopy
  1. float f1(float a, float b)  
  2. {  
  3.     //  
  4. }  
  5.   
  6. flaot f1(float a, float b, float c = 0)  
  7. {  
  8.     //  
  9. }  

下面的调用会产生歧义:

[c-sharp] view plaincopy
  1. f1(2.0, 2.0);  

言归正传,看下面一段代码:取自Effective C++

[c-sharp] view plaincopy
  1. class TextBlock {  
  2. public:  
  3. ...  
  4.     const charoperator[] (std::size_t position) const  
  5.     {return text[position];}  
  6.     charoperator[] (std::size_t position)  
  7.     {return text[position];}  
  8. private:  
  9.     std::string text;  
  10. }  
  11.   
  12. TextBlock tb("Hello");  
  13. std::cout << tb[0];  
  14.   
  15. const TextBlock ctb("World");  
  16. std::cout << ctb[0];  

const char& operator[] (std::size_t position) const

后一个const参与对重载函数的区分,这样在参数类型个数相同的情况下形成一种新的重载形式。

 

需要注意:常成员函数是常对象唯一的对外接口,使用使应该注意。常成员函数不能更新对象的数据成员,也不能调用该类中的普通成员函数。

 

这就是为什么const TextBlock ctb("World");会调用const char& operator[] (std::size_t position) const;的原因,包含了C++的隐式调用。


0 0