c++ const和指针*

3 篇文章 0 订阅
2 篇文章 0 订阅

左定值,右定向。

左定值:当const在的左侧时,指针所指向的值保持不变(或者说,不能通过指针来修改其所指向的值)。

右定向:当const在的右侧时,指针所指的方向保持不链。

例子 1-1

#include <iostream>
using namespace std;
int main(){
    const char* str1;
    str1 = "mystr1";
    str1[2] = 'c'; // 不允许:str1所指向的内容为定值(const),因此不允许通过str1修改
    cout << str1 << endl;
}

例子1-2

#include <iostream>
using namespace std;
int main(){
    int a = 8;
    const int* p = &a;
    *p = 9; // 不允许,p所指向的内容为定值(const),因此不允许通过p修改该值。
    cout << a << endl;
}

例子1-1,1-2都会报错,指针所值对象为定值,不可以通过指针进行修改。

error: read-only variable is not assignable

但是左定值情况下可以通过其他方式修改变量值,如下例子1-2b:

#include <iostream>
using namespace std;
int main(){
    int a = 8;
    const int* p = &a;
    // *p = 9; // 不允许,p所指向的内容为定值(const),因此不允许通过p修改该值。
    a = 9; // 允许,没有通过p来修改变量值
    cout << a << endl;
}

例子1-3

#include <iostream>
using namespace std;
int main(){
    const char* str1;
    str1 = "mystr1";
    str1 = "mystr1change"; // 允许:创建了一个新对象“mystr1change"并修改str1的指向。
    cout << str1 << endl;
}

例子1-4

#include <iostream>
using namespace std;

int main(){
    int a = 8;
    const int* p = &a;
    int b = 9;
    p = &b; // 允许,p指向一个新的对象b
    cout << *p << endl;
}

例子1-3,1-4程序正确,其直接修改了指针的指向。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值