美文网首页
c++ const修饰指针

c++ const修饰指针

作者: arkliu | 来源:发表于2022-11-16 08:02 被阅读0次

const关键字

#includ

e <iostream>
#include <stdlib.h>
using namespace std;


int main(void) {
    const int x = 3; // 添加const 关键字,表示不可变,类似于java的final 
    // x = 5;  // 编译错误,提示x为readonly 
    
    int const * p = &x;
    // *p = 5;  // 编译错误,提示x为readonly 
    
    int y = 5;
    int * const p = &x;  
    // p = &y; // 编译错误, 'p' has a previous declaration as `const int*p' 
    
    
    
    system("pause");
    return 0;
}

去掉数据类型:

常量指针

const 修饰* 表示 指针指向的内存不能被指针解引用修改

int a = 10;
int b = 30;
const int * p = &a;
// *p = 20; // error
p = &b;

指针常量

const 修饰变量名 表示指针的指向不能变,指针指向的内存可以通过指针解引用修改

int a = 10;
int b = 30;
int * const p = &a;
*p = 20; 
// p = &b; // error

常指针常量

指针指向的对象不能改变,同时指针指向的内存也不可以通过指针解引用修改

int a = 10;
int b = 30;
const int * const p = &a;
// *p = 20;  error
// p = &b; // error

相关文章

  • 常应用问题

    C++ const 常指针:const int* ptr;const 修饰int*,ptr指向整形常量,ptr指向...

  • 5.const与指针

    1.const修饰指针-常量指针 2.const修饰常量-指针常量 3.const修饰指针和常量 代码如下

  • iOS OC杂文

    1.const const修饰的是其右侧的内容const修饰的是只读的,const *修饰的是指针,所以指针是常量...

  • const修饰指针变量/引用/对象

    const修饰指针或者指针变量的区别 分辨的规则在于从const起往右读取 被修饰的是指针还是指针变量 const...

  • C语言-const指针

    const 指针 在普通指针类型前面,加上const修饰 例如: const 指针:区别 加不加const,有什么...

  • c++ const

    const 可修饰指针常量,可修饰常量指针,可以既修饰指针,也修饰常量常量指针:int a=10;int b=20...

  • C++之const修饰符(const修饰指针)

    const修饰指针无非三种情况:(1) const char * p(2) char const * p(3...

  • C++的Const修饰符几种用法

    1、const修饰符可以声明常量。 2、const修饰符可以声明指针,当const在(*)号左边,意味着指针指向的...

  • const,static,extern详解

    一、�const详解 �如果试图修改由const修饰符修饰所声明的变量,编译器会报错。�const修饰符修饰的指针...

  • c语言之const和指针

    const和指针 区别方法:如果const位于*的左侧,则const就是用来修饰指针所指向的变量,即指针指向为常量...

网友评论

      本文标题:c++ const修饰指针

      本文链接:https://www.haomeiwen.com/subject/vdirtdtx.html