美文网首页
C++ const常量

C++ const常量

作者: CoderGuogt | 来源:发表于2018-11-14 15:09 被阅读6次
  • Const是常量的意思,被其修饰的变量不可修改
  • 如果修饰的是类、结构体,那么其成员变量也不可修改
  • Const修饰的是其右边的内容

下面通过几个例子,具体了解一下Const

  1. const int *p
int age = 10;
const int *p = &age;

Const修饰的是右边的内容,得出*p是常量,p不是常量,所以直接修改p指向存储空间的内容是会报错的,也就是*p = 20;是编译不通过的;但是可以更改p的指向。

int age = 10;
// *p是常量,p不是常量
const int *p = &age;
// *p = 20; // *p是常量,不能修改,编译不通过
int height = 20;
p = &height;
    
cout << "age = " << age << endl;
cout << "*p = " << *p << endl;

运行结果:

age = 10
*p = 20

2.int *const p

int age = 10;
// p是常量,*p不是常量
int *const p = &age;
*p = 20;
int height = 40;
// p = &height; // p是常量,编译不通过
cout << "age = " << age << endl;
cout << "*p = " << *p << endl;    

运行结果:

age = 20
*p = 20

3.int const *p

int age = 10;
int height = 20;
// *p是常量,p不是常量
int const *p = &age;
cout << "*p = " << *p << endl;
// *p = 20; // *p是常量,编译不通过
p = &height;
cout << "age = " << age << endl;
cout << "*p = " << *p << endl;

运行结果:

*p = 10
age = 10
*p = 20

4.cont int *const p

int age = 10;
int height = 20;
// *p是常量,p是常量
const int *const p = &age;
cout << "*p = " << *p << endl;
// *p = 20; // *p是常量,编译不通过
// p = &height; // p是常量,编译不通过
cout << "age = " << age << endl;
cout << "*p = " << *p << endl;

运行结果:

*p = 10
age = 10
*p = 10

5.int const *const p

int age = 10;
int height = 20;
// *p是常量,p是常量
int const *const p = &age;
cout << "*p = " << *p << endl;
// *p = 20; // *p是常量,编译不通过
// p = &height; // p是常量,编译不通过
cout << "age = " << age << endl;
cout << "*p = " << *p << endl;

运行结果:

*p = 10
age = 10
*p = 10

相关文章

  • const常量与define宏定义的区别

    在C++ 程序中只使用const常量而不使用宏常量,即const常量完全取代宏常量。以下是const和define...

  • C++中的内联函数

    1、常量与宏回顾 C++中的const常量可以替代宏常数定义,如: const int A = 3; <===>...

  • C++程序设计学习笔记:1 从C走进C++ 关键字const和常

    1 定义常量 关键字const,用于定义常量。例如: 学了 C++ 之后,应该多用const,少用 define。...

  • 常应用问题

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

  • const 和 #define区别对待

    const和#define都可以用来定义常量 const:用来定义一个常量, 其实在 C++中,const 修饰的...

  • const理解

    关于const *和* const的理解,可以参考[C C++ OC指针常量和常量指针区别]这篇文章。 该篇文章中...

  • #define宏常量和const常量的区别

    C++ 语言可以用const来定义常量,也可以用#define来定义常量。但是前者比后者有更多的优点: const...

  • #define和const

    c语言只有#define,c++可以用#define和const来定义常量。const比#define更具优势。 ...

  • C++ const常量

    Const是常量的意思,被其修饰的变量不可修改 如果修饰的是类、结构体,那么其成员变量也不可修改 Const修饰的...

  • C++中const 关键字的用法(转)

    C++中const 关键字的用法 const修饰变量 const 主要用于把一个对象转换成一个常量,例如: 上面的...

网友评论

      本文标题:C++ const常量

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