const

const:它指定一个语义约束,编译器会强制实施这个约束。它告诉编译器和程序员它所指定的值是应该保持不变的。

    int a = 5;
    int b = 6;
    const int * p = &a;//*p是const的 
    int * const q = &a;//指针q是const的
    q = &b;//错误
    *p = b;//错误
    *q = b;
    p = &b;

const 出现在星号的左边表示被指物是常量,如果出现在右边表示指针本身是常量。

const int *p;
int const * p;//这两行的意义是一样的都是*p是常量

当我们在自己的class中重载*(乘法)号时应把它声明为const的

const myclass operator*(const myclass& lhs, const myclass& rhs);

把重载*的返回值声明为const是为了避免以下错误

if( a*b = c)//把==误输入为=

因为声明为了const所以编译器在这里会报错。否则- -.

const成员函数
注意:两个成员函数如果只有常量性(const)不同,它们就可以被重载。
eg:

class textbook{
publicconst char& operator[](int position) const
{
    return text[position];
}
char& operator[](int position)
{
    return text[position];
}
private:
    string text;    
}
void print( const textbook & c)//
{
    std::cout<<c[0];//这里调用的就是const operator[]
}

参考书籍:《Effective C++》

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值