浅谈c++11的const限定符

  1. const修饰函数
    目的是防止函数修改对象的数据成员,因此在const修饰的函数中不允许调用非const函数,因为非const函数可能会修改对象的数据成员。
#include <iostream>
class Test {
public:
    void set(int _a) {
        a = _a;
    }
    void output() const {
        //a = 5; 编译错误
        //cannot assign to non-static data member within const member function 'output'
        printf("%d\n", a); 
    }
private:
    int a;
};
int main() {
    Test test;
    test.set(10);
    test.output();
    return 0;
}

  1. 修饰函数参数
    const用来修饰函数参数,如果修饰的参数为按值传參,那么传入的参数不可以被修改,实际上意义并不是太大,如果参数为指针的时候,那么传入将会是实参,为了保证实参的值不会受到影响使用const进行保护,使得在函数体内不会改变实参的数据。
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <cstring>
#include <string.h>
const int MAX_DATA_SIZE = 1024;

void fun(const char * src, char * s) {
    //strcpy(src, s); 编译错误
}

int main() {
    char a[MAX_DATA_SIZE] = "--------", b[MAX_DATA_SIZE] = "**********";
    fun();
    return 0;
}

注:const指针可以接受非const指针参数,但是非const指针不能接受const指针参数。
3. 常量指针
常量指针可以理解为指向常量的指针变量写法为

const int * p;

我们可以理解为 **p is a pointer to const int(从后向前读)**即为p是一个指针指向常量int,接下来我们用代码演示一下

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <cstring>
#include <string.h>
const int MAX_DATA_SIZE = 1024;

int main() {
    int a = 5, b = 6;
    const int * p = &a;
    *p = b;// 编译错误
    p = &b;
    return 0;
}
  1. 指针常量
    与常量指针不同,指针常量的本质就是个常量不可改变,只是用指针来修饰它,后来不可修改,但是他指向的值可以修改。
    写法为:
int * const p;
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <cstring>
#include <string.h>
const int MAX_DATA_SIZE = 1024;

int main() {
    int a = 5, b = 6;
    int * const p = &a;
    *p = b;
    p = &b; //编译错误
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值