谈谈const

一、const member functions(const成员函数)

例子:const String str("hello world");

          str.print();

          如果当初设计String::print()时未指明const,那么上行便是经由const object调用non-const member function,会出错。此非吾人所愿

二.const成员函数重载

当成员函数的const和non-const版本同时存在,const object只能调用const版本,non-const object只能调用non-const版本;

class template std::basic_string<…> 有如下两个member functions: 
charT operator[](size_type pos) const {
    /不必考虑 Copy on Write /
} 
reference operator[](size_type pos) {
    /必须考虑 Copy on Write /
}
COW:Copy on Write

const string s1("hello world");  cout << s1[0];  // 调用const版本

string s2("hello world");  s2[0] = "t"; // 调用非const版本

三.总结

1. const修饰的成员函数,不仅限制函数去修改成员变量,同时也可以实现函数的重载 
2. const修饰的成员函数,如果没有被重载,那么非const对象和const对象都可以调用; 
3. const修饰的成员函数,如果被重载了,非const对象只能调用没有被const修饰的成员函数,const对象也只能调用被const修饰的成员函数。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值