常见的const应用

const定义变量

const定义变量后,该变量就没有了写权限,只有读权限

1.const用于定义变量时,要进行初始化

例如:
const int a = 10; //合法
const int a; //非法

2.数据类型对于const而言是透明的

例如:
const int a = 10; 等价于 int const a = 10;
const int* p1 = &a; 等价于 int const* p1 = &a;
但是这里要注意
const int* p1 = &a; 不等价于 int* const p1 = &a;

const int* p1 = &a; 指const修饰的是 *p1,即 *p1不可以被修改,内容是只读的;但是 p1 可以修改,可以指向其它的地址空间。

int* const p1 = &a; 指const修饰的是 p1,即 p1 不可以被修改,不能指向其它地址空间,但是 *p1 可以修改,内容可读可写。

如下代码给出了二者之间的使用区别:

#include <iostream>

int main()
{
    int i = 10;
    int j = 20;
    int const* p2 = &i;
    int* const p3 = &j;
    p2 = &j;             //正确,因为const是对*p2进行限制的,不影响p2
    *p3 = 20;            //正确,因为const是对p3进行限制的,不影响*p3
    //*p2 = 30;          //错误,因为*p2已经被const修饰了,不能再次修改
    //p3 = &j;           //错误,因为p3已经被const修饰了,不能再次修改
    return 0;
}

3.权限只能同等传递或者缩小传递
简单的一句话:非const可以调用const,const不可以调用非const

const修饰函数返回值

当const修饰函数返回值时,该返回值不能被改变

const成员函数

  • const成员函数可以访问非const对象的非const数据成员、const数据成员,也可以访问const对象内的所有数据成员,但不能修改任何变量;非const成员函数可以访问非const对象的数据成员、const数据成员,但不可以访问const对象的任意数据成员。
  • const成员函数只能用于非静态成员函数,不能用于静态成员函数
class Date
{
public:
    Date& operator=(const Date& d)
    {
        if (this != &d)
        {
            _year = d._year;
            _month = d._month;
            _day = d._day;
        }
        return *this;
    }

    void Print()
    {
        cout << _year << "-" << _month << "-" << _day << endl;
    }
private:
    int _year;
    int _month;
    int _day;
};

在上面的Date类中,我们为了防止在 operator= 函数中对象 d 修改私有成员变量,则可以加上const限定符。
但是在 Print 函数中如何给 this指针加上const限定符?
    因为C++中函数形参 this指针是隐含的,不允许显示的写出来,所以规定 const 写在成员函数的后面。

    void Print()const
    {
        cout << _year << "-" << _month << "-" << _day << endl;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值