专业编程基础技术教程

网站首页 > 基础教程 正文

C++基础概念:const关键字

ccvgpt 2024-08-08 12:55:34 基础教程 11 ℃

1) 定义常量

有时候我们希望定义这样一种变量, 它的值不能被改变。

C++基础概念:const关键字

为了满足这一 要求, 可以用关键字 const 对变量的类型加以限定。

const对象一旦创建后其值就不能再改变,所以const对象必须在定义的时候就初始化。

初始值可以是任意复杂的表达式。

与非const类型所能参与的操作相比,const 类型的对象能完成其中大部分;

主要的限制就是只能在 const 类型的对象上执行不改变其内容的操作


// const int max ; //error: uninitialized const 'max'
 const int max = 100 ;
 cout << max << endl ;
 int j = max ;
 cout << j << endl ;
// max = j ; //error: assignment of read-only variable 'max'


const定义常量与define的区别:

const是有类型的,可以做类型检查;define只是替换,是没有类型检查的,容易出错。

所以在C++推荐的做法是使用const,不推荐使用define


2) 定义常量指针

const T *用于定义常量指针。

不可通过常量指针修改其指向的内容

 int n = 4 ;
 const int *p = &n ;
// *p = 5 ; // error: assignment of read-only location '* p'

常量指针指向的位置可以变化

 int n = 4 ;
 const int *p = &n ;
 n =5 ;
 int m = 6 ;
 p = &m ;
 cout << *p << endl ;

不能把常量指针赋值给非常量指针,反过来可以

 int n = 4 ;
 const int *p = &n ;
 n =5 ;
 int m = 6 ;
 p = &m ;
 int * p2 = &n ;
 p = p2 ; // no error
 cout << *p << endl ;
// p2 = p ; //error: invalid conversion from 'const int*' to 'int*'

3) 定义常引用

不能通过常引用修改其引用的变量

 const int &r = m ;
 cout << r << endl ;
// r = n ; //error: assignment of read-only reference 'r'

const T 类型的常变量和 const T & 类型的引用则不能用来初始化 T & 类型的引用

T &类型的引用 或 T类型的变量可以用来初始化 const T & 类型的引用。

 int & r = m ;
 const int &t = r ;
// int & y = t ; // error: binding reference of type 'int&' to 'const int' discards qualifiers

参考代码:

#include <iostream>
#include <cstdio>
using namespace std;
int main ()
{
// const int max ; //error: uninitialized const 'max'
 const int max = 100 ;
 cout << max << endl ;
 int j = max ;
 cout << j << endl ;
// max = j ; //error: assignment of read-only variable 'max'
 int n = 4 ;
 const int *p = &n ;
// *p = 5 ; // error: assignment of read-only location '* p'
 cout << *p << endl ;
 n =5 ;
 cout << *p << endl ;
 int m = 6 ;
 p = &m ;
 cout << *p << endl ;
 int * p2 = &n ;
 p = p2 ;
 cout << *p << endl ;
// p2 = p ; //error: invalid conversion from 'const int*' to 'int*'
 int & r = m ;
 const int &t = r ;
 cout << t << endl ;
// t = n ; //error: assignment of read-only reference 't'
// int & y = t ; // error: binding reference of type 'int&' to 'const int' discards qualifiers
 return 0 ;
}


输出结果:

g++ const_pointer.cpp
./a.out
100
100
4
5
6
5
6

Tags:

最近发表
标签列表